From noreply at r-forge.r-project.org Sun Feb 1 20:50:19 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 1 Feb 2015 20:50:19 +0100 (CET) Subject: [Returnanalytics-commits] r3588 - in pkg/FactorAnalytics: . R man Message-ID: <20150201195019.CC1BE187987@r-forge.r-project.org> Author: chenyian Date: 2015-02-01 20:50:19 +0100 (Sun, 01 Feb 2015) New Revision: 3588 Added: pkg/FactorAnalytics/R/fitTsfmTiming.r pkg/FactorAnalytics/man/fitTsfmTiming.Rd Modified: pkg/FactorAnalytics/NAMESPACE pkg/FactorAnalytics/R/fitTsfm.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/fmCov.Rd pkg/FactorAnalytics/man/fmEsDecomp.Rd pkg/FactorAnalytics/man/fmSdDecomp.Rd pkg/FactorAnalytics/man/fmVaRDecomp.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/predict.sfm.Rd pkg/FactorAnalytics/man/predict.tsfm.Rd pkg/FactorAnalytics/man/print.pafm.Rd pkg/FactorAnalytics/man/print.sfm.Rd pkg/FactorAnalytics/man/print.tsfm.Rd pkg/FactorAnalytics/man/summary.pafm.Rd pkg/FactorAnalytics/man/summary.sfm.Rd pkg/FactorAnalytics/man/summary.tsfm.Rd Log: Add a new function fitTsfmTiming.r and fitTsfmTiming.Rd. Modified: pkg/FactorAnalytics/NAMESPACE =================================================================== --- pkg/FactorAnalytics/NAMESPACE 2015-01-27 08:36:37 UTC (rev 3587) +++ pkg/FactorAnalytics/NAMESPACE 2015-02-01 19:50:19 UTC (rev 3588) @@ -1,62 +1,63 @@ -# Generated by roxygen2 (4.0.2): do not edit by hand - -S3method(coef,sfm) -S3method(coef,tsfm) -S3method(fitted,sfm) -S3method(fitted,tsfm) -S3method(fmCov,sfm) -S3method(fmCov,tsfm) -S3method(fmEsDecomp,sfm) -S3method(fmEsDecomp,tsfm) -S3method(fmSdDecomp,sfm) -S3method(fmSdDecomp,tsfm) -S3method(fmVaRDecomp,sfm) -S3method(fmVaRDecomp,tsfm) -S3method(plot,pafm) -S3method(plot,sfm) -S3method(plot,tsfm) -S3method(predict,sfm) -S3method(predict,tsfm) -S3method(print,pafm) -S3method(print,sfm) -S3method(print,summary.sfm) -S3method(print,summary.tsfm) -S3method(print,tsfm) -S3method(residuals,sfm) -S3method(residuals,tsfm) -S3method(summary,pafm) -S3method(summary,sfm) -S3method(summary,tsfm) -export(dCornishFisher) -export(fitSfm) -export(fitTsfm) -export(fmCov) -export(fmEsDecomp) -export(fmSdDecomp) -export(fmVaRDecomp) -export(pCornishFisher) -export(paFm) -export(qCornishFisher) -export(rCornishFisher) -importFrom(MASS,ginv) -importFrom(PerformanceAnalytics,Return.cumulative) -importFrom(PerformanceAnalytics,VaR) -importFrom(PerformanceAnalytics,chart.ACFplus) -importFrom(PerformanceAnalytics,chart.Histogram) -importFrom(PerformanceAnalytics,chart.QQPlot) -importFrom(PerformanceAnalytics,chart.TimeSeries) -importFrom(PerformanceAnalytics,checkData) -importFrom(corrplot,corrplot) -importFrom(lars,cv.lars) -importFrom(lars,lars) -importFrom(lattice,barchart) -importFrom(lattice,panel.barchart) -importFrom(lattice,panel.grid) -importFrom(lattice,xyplot) -importFrom(leaps,regsubsets) -importFrom(lmtest,coeftest.default) -importFrom(robust,lmRob) -importFrom(robust,step.lmRob) -importFrom(sandwich,vcovHAC.default) -importFrom(sandwich,vcovHC.default) -importFrom(strucchange,efp) +# Generated by roxygen2 (4.0.2): do not edit by hand + +S3method(coef,sfm) +S3method(coef,tsfm) +S3method(fitted,sfm) +S3method(fitted,tsfm) +S3method(fmCov,sfm) +S3method(fmCov,tsfm) +S3method(fmEsDecomp,sfm) +S3method(fmEsDecomp,tsfm) +S3method(fmSdDecomp,sfm) +S3method(fmSdDecomp,tsfm) +S3method(fmVaRDecomp,sfm) +S3method(fmVaRDecomp,tsfm) +S3method(plot,pafm) +S3method(plot,sfm) +S3method(plot,tsfm) +S3method(predict,sfm) +S3method(predict,tsfm) +S3method(print,pafm) +S3method(print,sfm) +S3method(print,summary.sfm) +S3method(print,summary.tsfm) +S3method(print,tsfm) +S3method(residuals,sfm) +S3method(residuals,tsfm) +S3method(summary,pafm) +S3method(summary,sfm) +S3method(summary,tsfm) +export(dCornishFisher) +export(fitSfm) +export(fitTsfm) +export(fitTsfmTiming) +export(fmCov) +export(fmEsDecomp) +export(fmSdDecomp) +export(fmVaRDecomp) +export(pCornishFisher) +export(paFm) +export(qCornishFisher) +export(rCornishFisher) +importFrom(MASS,ginv) +importFrom(PerformanceAnalytics,Return.cumulative) +importFrom(PerformanceAnalytics,VaR) +importFrom(PerformanceAnalytics,chart.ACFplus) +importFrom(PerformanceAnalytics,chart.Histogram) +importFrom(PerformanceAnalytics,chart.QQPlot) +importFrom(PerformanceAnalytics,chart.TimeSeries) +importFrom(PerformanceAnalytics,checkData) +importFrom(corrplot,corrplot) +importFrom(lars,cv.lars) +importFrom(lars,lars) +importFrom(lattice,barchart) +importFrom(lattice,panel.barchart) +importFrom(lattice,panel.grid) +importFrom(lattice,xyplot) +importFrom(leaps,regsubsets) +importFrom(lmtest,coeftest.default) +importFrom(robust,lmRob) +importFrom(robust,step.lmRob) +importFrom(sandwich,vcovHAC.default) +importFrom(sandwich,vcovHC.default) +importFrom(strucchange,efp) Modified: pkg/FactorAnalytics/R/fitTsfm.R =================================================================== --- pkg/FactorAnalytics/R/fitTsfm.R 2015-01-27 08:36:37 UTC (rev 3587) +++ pkg/FactorAnalytics/R/fitTsfm.R 2015-02-01 19:50:19 UTC (rev 3588) @@ -1,584 +1,584 @@ -#' @title Fit a time series factor model using time series regression -#' -#' @description Fits a time series (a.k.a. macroeconomic) factor model for one -#' or more 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 compute excess returns. -#' -#' Estimation method "OLS" corresponds to ordinary least squares using -#' \code{\link[stats]{lm}}, "DLS" is discounted least squares (weighted least -#' squares with exponentially declining weights that sum to unity), and, -#' "Robust" is robust regression (using \code{\link[robust]{lmRob}}). -#' -#' If \code{variable.selection="none"}, uses all the factors and performs no -#' variable selection. Whereas, "stepwise" performs traditional stepwise -#' LS or Robust regression (using \code{\link[stats]{step}} or -#' \code{\link[robust]{step.lmRob}}), that starts from the initial set of -#' factors and adds/subtracts factors only if the regression fit, as measured -#' by the Bayesian Information Criterion (BIC) or Akaike Information Criterion -#' (AIC), improves. And, "subsets" enables subsets selection using -#' \code{\link[leaps]{regsubsets}}; chooses the best performing subset of any -#' given size or within a range of subset sizes. Different methods such as -#' exhaustive search (default), forward or backward stepwise, or sequential -#' replacement can be employed.See \code{\link{fitTsfm.control}} for more -#' details on the control arguments. -#' -#' \code{variable.selection="lars"} corresponds to least angle regression -#' using \code{\link[lars]{lars}} with variants "lasso" (default), "lar", -#' "stepwise" or "forward.stagewise". Note: If \code{variable.selection="lars"}, -#' \code{fit.method} will be ignored. -#' -#' Arguments \code{mkt.name} and \code{mkt.timing} allow for market-timing -#' factors to be added to any of the above methods. Market timing accounts for -#' the price movement of the general stock market relative to fixed income -#' securities. Specifying \code{mkt.timing="HM"}, includes -#' $down.market = max(0, R_f-R_m)$ as a factor, following Henriksson & Merton -#' (1981). The coefficient of this down-market factor can be interpreted as the -#' number of "free" put options on the market provided by the manager's -#' market-timings kills. Similarly, to account for market timing with respect -#' to volatility, one can specify \code{mkt.timing="TM"}. Following -#' Treynor & Mazuy (1966), $market.sqd = (R_m-R_f)^2$ is added as a factor. -#' For example, as a test for market timing, either of these factors can be -#' added to the single index regression model. -#' -#' \subsection{Data Processing}{ -#' -#' Note about NAs: Before model fitting, incomplete cases are removed for -#' every asset (return data combined with respective factors' return data) -#' using \code{\link[stats]{na.omit}}. Otherwise, all observations in -#' \code{data} are included. -#' -#' Note about \code{asset.names} and \code{factor.names}: Spaces in column -#' names of \code{data} will be converted to periods as \code{fitTsfm} works -#' with \code{xts} objects internally and colnames won't be left as they are. -#' } -#' -#' @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 mkt.name name of the column for market excess returns (Rm-Rf); this -#' is necessary to add market timing factors. Default is NULL. -#' @param rf.name name of the column of risk free rate variable to calculate -#' excess returns for all assets (in \code{asset.names}) and factors (in -#' \code{factor.names}). Default is NULL, and no action is taken. -#' @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{mkt.name} and \code{rf.name}. -#' @param fit.method the estimation method, one of "OLS", "DLS" or "Robust". -#' See details. Default is "OLS". -#' @param variable.selection the variable selection method, one of "none", -#' "stepwise","subsets","lars". See details. Default is "none". -#' @param mkt.timing one of "HM" or "TM". See Details. Default is NULL. -#' \code{mkt.name} is required if any of these options are to be implemented. -#' @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}} -#' -#' @return fitTsfm returns an object of class \code{"tsfm"} for which -#' \code{print}, \code{plot}, \code{predict} and \code{summary} methods exist. -#' -#' The generic accessor functions \code{coef}, \code{fitted} and -#' \code{residuals} extract various useful features of the fit object. -#' Additionally, \code{fmCov} computes the covariance matrix for asset returns -#' based on the fitted factor model -#' -#' 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}{length-N vector of estimated alphas.} -#' \item{beta}{N x K matrix 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 -#' \code{variable.selection="lars"}} -#' \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, Sangeetha Srinivasan and Yi-An Chen. -#' -#' @references -#' Christopherson, J. A., Carino, D. R., & Ferson, W. E. (2009). Portfolio -#' performance measurement and benchmarking. McGraw Hill Professional. -#' -#' Efron, B., Hastie, T., Johnstone, I., & Tibshirani, R. (2004). Least angle -#' regression. The Annals of statistics, 32(2), 407-499. -#' -#' Hastie, T., Tibshirani, R., Friedman, J., Hastie, T., Friedman, J., & -#' Tibshirani, R. (2009). The elements of statistical learning (Vol. 2, No. 1). -#' New York: Springer. -#' -#' Henriksson, R. D., & Merton, R. C. (1981). On market timing and investment -#' performance. II. Statistical procedures for evaluating forecasting skills. -#' Journal of business, 513-533. -#' -#' Treynor, J., & Mazuy, K. (1966). Can mutual funds outguess the market. -#' Harvard business review, 44(4), 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[stats]{fitted}}, \code{\link[stats]{residuals}}, -#' \code{\link{fmCov}}, \code{\link{fmSdDecomp}}, \code{\link{fmVaRDecomp}} -#' and \code{\link{fmEsDecomp}}. -#' -#' \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)]), data=managers) -#' summary(fit) -#' fitted(fit) -#' # 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: Market-timing factors with robust fit -#' fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), factor.names=NULL, -#' mkt.name="SP500 TR", mkt.timing="HM", data=managers, -#' fit.method="Robust") -#' -#' # example using "subsets" variable selection -#' fit.sub <- fitTsfm(asset.names=colnames(managers[,(1:6)]), -#' factor.names=colnames(managers[,(7:9)]), -#' data=managers, variable.selection="subsets", -#' method="exhaustive", nvmin=2) -#' -#' # example using "lars" variable selection and subtracting risk-free rate -#' fit.lar <- fitTsfm(asset.names=colnames(managers[,(1:6)]), -#' factor.names=colnames(managers[,(7:9)]), -#' rf.name="US 3m TR", data=managers, -#' variable.selection="lars", lars.criterion="cv") -#' -#' @importFrom PerformanceAnalytics checkData -#' @importFrom robust lmRob step.lmRob -#' @importFrom leaps regsubsets -#' @importFrom lars lars cv.lars -#' -#' @export - -fitTsfm <- function(asset.names, factor.names, mkt.name=NULL, rf.name=NULL, - data=data, fit.method=c("OLS","DLS","Robust"), - variable.selection=c("none","stepwise","subsets","lars"), - mkt.timing=NULL, control=fitTsfm.control(...), ...) { - - # record the call as an element to be returned - call <- match.call() - - # set defaults and check input vailidity - fit.method = fit.method[1] - if (!(fit.method %in% c("OLS","DLS","Robust"))) { - stop("Invalid argument: fit.method must be 'OLS', 'DLS' or 'Robust'") - } - variable.selection = variable.selection[1] - if (!(variable.selection %in% c("none","stepwise","subsets","lars"))) { - stop("Invalid argument: variable.selection must be either 'none', - 'stepwise','subsets' or 'lars'") - } - if (missing(factor.names) && !is.null(mkt.name)) { - factor.names <- NULL - } - - if (xor(is.null(mkt.name), is.null(mkt.timing))) { - stop("Missing argument: Both mkt.name and mkt.timing are necessary to add - market timing factors") - } - - # extract arguments to pass to different fit and variable selection functions - decay <- control$decay - nvmin <- control$nvmin - lars.criterion <- control$lars.criterion - m1 <- match(c("weights","model","x","y","qr"), - names(control), 0L) - lm.args <- control[m1, drop=TRUE] - m2 <- match(c("weights","model","x","y","nrep"), - names(control), 0L) - lmRob.args <- control[m2, drop=TRUE] - m3 <- match(c("scope","scale","direction","trace","steps","k"), - names(control), 0L) - step.args <- control[m3, drop=TRUE] - m4 <- match(c("weights","nvmax","force.in","force.out","method", - "really.big"), names(control), 0L) - regsubsets.args <- control[m4, drop=TRUE] - m5 <- match(c("type","normalize","eps","max.steps","trace"), - names(control), 0L) - lars.args <- control[m5, drop=TRUE] - m6 <- match(c("K","type","normalize","eps","max.steps","trace"), - names(control), 0L) - cv.lars.args <- control[m6, drop=TRUE] - - # convert data into an xts object and hereafter work with xts objects - data.xts <- checkData(data) - # convert index to 'Date' format for uniformity - time(data.xts) <- as.Date(time(data.xts)) - - # 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)))) - } else { - warning("Excess returns were not computed.") - } - - # opt add mkt-timing factors: down.market=max(0,Rf-Rm), market.sqd=(Rm-Rf)^2 - if("HM" %in% mkt.timing) { - down.market <- data.xts[,mkt.name] - down.market [down.market > 0] <- 0 - dat.xts <- merge.xts(dat.xts,down.market) - colnames(dat.xts)[dim(dat.xts)[2]] <- "down.market" - factor.names <- c(factor.names, "down.market") - } - if("TM" %in% mkt.timing) { - market.sqd <- data.xts[,mkt.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, lm.args, lmRob.args, decay) - } else if (variable.selection == "stepwise") { - reg.list <- SelectStepwise(dat.xts, asset.names, factor.names, fit.method, - lm.args, lmRob.args, step.args, decay) - } else if (variable.selection == "subsets") { - reg.list <- SelectAllSubsets(dat.xts, asset.names, factor.names, fit.method, - lm.args, lmRob.args, regsubsets.args, - nvmin, decay) - } else if (variable.selection == "lars") { - result.lars <- SelectLars(dat.xts, asset.names, factor.names, lars.args, - cv.lars.args, lars.criterion) - input <- list(call=call, data=dat.xts, asset.names=asset.names, - factor.names=factor.names, fit.method=NULL, - variable.selection=variable.selection) - result <- c(result.lars, input) - class(result) <- "tsfm" - return(result) - } - - # 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] - # reorder and expand columns of beta to match factor.names - tmp <- matrix(NA, length(asset.names), length(factor.names)) - colnames(tmp) <- factor.names - rownames(tmp) <- asset.names - beta <- merge(beta, tmp, all.x=TRUE, sort=FALSE)[,factor.names, drop=FALSE] - rownames(beta) <- asset.names - # extract r2 and residual sd - 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, - lm.args, lmRob.args, 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]] <- do.call(lm, c(list(fm.formula,data=reg.xts),lm.args)) - } else if (fit.method == "DLS") { - lm.args$weights <- WeightsDLS(nrow(reg.xts), decay) - reg.list[[i]] <- do.call(lm, c(list(fm.formula,data=reg.xts),lm.args)) - } else if (fit.method == "Robust") { - reg.list[[i]] <- do.call(lmRob, c(list(fm.formula,data=reg.xts), - lmRob.args)) - } - } - reg.list -} - - -### method variable.selection = "stepwise" -# -SelectStepwise <- function(dat.xts, asset.names, factor.names, fit.method, - lm.args, lmRob.args, step.args, 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") { - lm.fit <- do.call(lm, c(list(fm.formula,data=reg.xts),lm.args)) - reg.list[[i]] <- do.call(step, c(list(lm.fit),step.args)) - } else if (fit.method == "DLS") { - lm.args$weights <- WeightsDLS(nrow(reg.xts), decay) - lm.fit <- do.call(lm, c(list(fm.formula,data=reg.xts),lm.args)) - reg.list[[i]] <- do.call(step, c(list(lm.fit),step.args)) - } else if (fit.method == "Robust") { - lmRob.fit <- do.call(lmRob, c(list(fm.formula,data=reg.xts), lmRob.args)) - reg.list[[i]] <- do.call(step.lmRob, c(list(lmRob.fit), step.args)) - } - } - reg.list -} - - -### method variable.selection = "subsets" -# -SelectAllSubsets <- function(dat.xts, asset.names, factor.names, fit.method, - lm.args, lmRob.args, regsubsets.args, nvmin, - 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," ~ .")) - - if (fit.method=="DLS" && !"weights" %in% names(regsubsets.args)) { - regsubsets.args$weights <- WeightsDLS(nrow(reg.xts), decay) - } - - # choose best subset of factors depending on specified subset size - fm.subsets <- do.call(regsubsets, c(list(fm.formula,data=reg.xts), - regsubsets.args)) - sum.sub <- summary(fm.subsets) - - # choose best model of a given subset size nvmax=nvmin (or) - # best model amongst subset sizes in [nvmin, nvmax] - nvmax <- length(sum.sub$bic) - best.size <- which.min(sum.sub$bic[nvmin:nvmax]) + nvmin -1 - names.sub <- names(which(sum.sub$which[best.size,-1]==TRUE)) - bic <- min(sum.sub$bic[nvmin:nvmax]) - - # completely remove NA cases for chosen subset - reg.xts <- na.omit(dat.xts[,c(i,names.sub)]) - - # fit based on time series regression method chosen - if (fit.method == "OLS") { - reg.list[[i]] <- do.call(lm, c(list(fm.formula,data=reg.xts),lm.args)) - } else if (fit.method == "DLS") { - lm.args$weights <- WeightsDLS(nrow(reg.xts), decay) - reg.list[[i]] <- do.call(lm, c(list(fm.formula,data=reg.xts),lm.args)) - } else if (fit.method == "Robust") { - reg.list[[i]] <- do.call(lmRob, c(list(fm.formula,data=reg.xts), - lmRob.args)) - } - } - reg.list -} - - -### method variable.selection = "lars" -# -SelectLars <- function(dat.xts, asset.names, factor.names, lars.args, - cv.lars.args, lars.criterion) { - # initialize list object to hold the fitted objects and, vectors and matrices - # for the other results - asset.fit <- list() - fitted.list <- list() - alpha <- rep(NA, length(asset.names)) - beta <- matrix(NA, length(asset.names), length(factor.names)) - r2 <- rep(NA, length(asset.names)) - resid.sd <- rep(NA, length(asset.names)) - names(alpha)=names(r2)=names(resid.sd)=rownames(beta)=asset.names - colnames(beta) <- factor.names - - # 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)]) - # convert to matrix - reg.mat <- as.matrix(reg.xts) - # fit lars regression model - lars.fit <- do.call(lars, c(list(x=reg.mat[,factor.names],y=reg.mat[,i]), - lars.args)) - lars.sum <- summary(lars.fit) - lars.cv <- do.call(cv.lars, c(list(x=reg.mat[,factor.names],y=reg.mat[,i], - mode="step"),cv.lars.args)) - # including plot.it=FALSE to cv.lars strangely gives an error: "Argument s - # out of range". And, specifying index=seq(nrow(lars.fit$beta)-1) resolves - # the issue, but care needs to be taken for small N - - # get the step that minimizes the "Cp" statistic or - # the K-fold "cv" mean-squared prediction error - if (lars.criterion=="Cp") { - s <- which.min(lars.sum$Cp)-1 # 2nd row is "step 1" - } else { - s <- which.min(lars.cv$cv)-1 - } - # get factor model coefficients & fitted values at the step obtained above - coef.lars <- predict(lars.fit, s=s, type="coef", mode="step") - fitted.lars <- predict(lars.fit, reg.mat[,factor.names], s=s, type="fit", - mode="step") - fitted.list[[i]] <- xts(fitted.lars$fit, index(reg.xts)) - # extract and assign the results - asset.fit[[i]] = lars.fit - alpha[i] <- (fitted.lars$fit - - reg.xts[,factor.names]%*%coef.lars$coefficients)[1] - beta.names <- names(coef.lars$coefficients) - beta[i, beta.names] <- coef.lars$coefficients - r2[i] <- lars.fit$R2[s+1] - resid.sd[i] <- sqrt(lars.sum$Rss[s+1]/(nrow(reg.xts)-lars.sum$Df[s+1])) - - } - if (length(asset.names)>1) { - fitted.xts <- do.call(merge, fitted.list) - } else { - fitted.xts <- fitted.list[[1]] - } - results.lars <- list(asset.fit=asset.fit, alpha=alpha, beta=beta, r2=r2, - resid.sd=resid.sd, fitted=fitted.xts) - # As a special case for variable.selection="lars", fitted values are also - # returned by fitTsfm. Else, step s from the best fit is needed to get - # fitted values & residuals. -} - - -### calculate exponentially decaying weights for fit.method="DLS" -## t = number of observations; d = decay factor -# -WeightsDLS <- function(t,d) { - # more weight given to more recent observations - w <- d^seq((t-1),0,-1) - # ensure that the weights sum to unity - w/sum(w) -} - -### make a data frame (padded with NAs) from unequal vectors with named rows -## l = list of unequal vectors -# -makePaddedDataFrame <- function(l) { - DF <- do.call(rbind, lapply(lapply(l, unlist), "[", - unique(unlist(c(sapply(l,names)))))) - DF <- as.data.frame(DF) - names(DF) <- unique(unlist(c(sapply(l,names)))) - # as.matrix(DF) # if matrix output needed - DF -} - -#' @param object a fit object of class \code{tsfm} which is returned by -#' \code{fitTsfm} - -#' @rdname fitTsfm -#' @method coef tsfm -#' @export - -coef.tsfm <- function(object, ...) { - # cbind alpha and beta; works for all fit and var selection methods - coef.mat <- cbind(object$alpha, object$beta) - # name for alpha/intercept column - colnames(coef.mat)[1] <- "(Intercept)" - return(coef.mat) -} - -#' @rdname fitTsfm -#' @method fitted tsfm -#' @export - -fitted.tsfm <- function(object, ...) { - if (object$variable.selection=="lars") { - # generic method 'fitted' does not exist for "lars" fit objects - # so, use fitted values returned by 'fitTsfm' - fitted.xts <- object$fitted - } else { - if (length(object$asset.names)>1) { - # get fitted values from each linear factor model fit - # and convert them into xts/zoo objects - fitted.list = sapply(object$asset.fit, - function(x) checkData(fitted(x,...))) - # this is a list of xts objects, indexed by the asset name - # merge the objects in the list into one xts object - fitted.xts <- do.call(merge, fitted.list) - } else { - fitted.xts <- checkData(fitted(object$asset.fit[[1]],...)) - colnames(fitted.xts) <- object$asset.names - } - } - time(fitted.xts) <- as.Date(time(fitted.xts)) - return(fitted.xts) -} - - -#' @rdname fitTsfm -#' @method residuals tsfm -#' @export - -residuals.tsfm <- function(object, ...) { - if (object$variable.selection=="lars") { - # generic method 'residuals' does not exist for "lars" fit objects - # so, calculate them from the actual and fitted values - residuals.xts <- object$data[,object$asset.names] - object$fitted - } else { - if (length(object$asset.names)>1) { - # get residuals from each linear factor model fit - # and convert them into xts/zoo objects - residuals.list = sapply(object$asset.fit, - function(x) checkData(residuals(x,...))) - # this is a list of xts objects, indexed by the asset name - # merge the objects in the list into one xts object - residuals.xts <- do.call(merge, residuals.list) - } else { - residuals.xts <- checkData(residuals(object$asset.fit[[1]],...)) - colnames(residuals.xts) <- object$asset.names - } - } - time(residuals.xts) <- as.Date(time(residuals.xts)) - return(residuals.xts) -} +#' @title Fit a time series factor model using time series regression +#' +#' @description Fits a time series (a.k.a. macroeconomic) factor model for one +#' or more 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 compute excess returns. +#' +#' Estimation method "OLS" corresponds to ordinary least squares using +#' \code{\link[stats]{lm}}, "DLS" is discounted least squares (weighted least +#' squares with exponentially declining weights that sum to unity), and, +#' "Robust" is robust regression (using \code{\link[robust]{lmRob}}). +#' +#' If \code{variable.selection="none"}, uses all the factors and performs no +#' variable selection. Whereas, "stepwise" performs traditional stepwise +#' LS or Robust regression (using \code{\link[stats]{step}} or +#' \code{\link[robust]{step.lmRob}}), that starts from the initial set of +#' factors and adds/subtracts factors only if the regression fit, as measured +#' by the Bayesian Information Criterion (BIC) or Akaike Information Criterion +#' (AIC), improves. And, "subsets" enables subsets selection using +#' \code{\link[leaps]{regsubsets}}; chooses the best performing subset of any +#' given size or within a range of subset sizes. Different methods such as +#' exhaustive search (default), forward or backward stepwise, or sequential +#' replacement can be employed.See \code{\link{fitTsfm.control}} for more +#' details on the control arguments. +#' +#' \code{variable.selection="lars"} corresponds to least angle regression +#' using \code{\link[lars]{lars}} with variants "lasso" (default), "lar", +#' "stepwise" or "forward.stagewise". Note: If \code{variable.selection="lars"}, +#' \code{fit.method} will be ignored. +#' +#' Arguments \code{mkt.name} and \code{mkt.timing} allow for market-timing +#' factors to be added to any of the above methods. Market timing accounts for +#' the price movement of the general stock market relative to fixed income +#' securities. Specifying \code{mkt.timing="HM"}, includes +#' $down.market = max(0, R_f-R_m)$ as a factor, following Henriksson & Merton +#' (1981). The coefficient of this down-market factor can be interpreted as the +#' number of "free" put options on the market provided by the manager's +#' market-timings kills. Similarly, to account for market timing with respect +#' to volatility, one can specify \code{mkt.timing="TM"}. Following +#' Treynor & Mazuy (1966), $market.sqd = (R_m-R_f)^2$ is added as a factor. +#' For example, as a test for market timing, either of these factors can be +#' added to the single index regression model. +#' +#' \subsection{Data Processing}{ +#' +#' Note about NAs: Before model fitting, incomplete cases are removed for +#' every asset (return data combined with respective factors' return data) +#' using \code{\link[stats]{na.omit}}. Otherwise, all observations in +#' \code{data} are included. +#' +#' Note about \code{asset.names} and \code{factor.names}: Spaces in column +#' names of \code{data} will be converted to periods as \code{fitTsfm} works [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3588 From noreply at r-forge.r-project.org Mon Feb 2 21:15:56 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 2 Feb 2015 21:15:56 +0100 (CET) Subject: [Returnanalytics-commits] r3589 - in pkg/FactorAnalytics: R man Message-ID: <20150202201556.5A72C186D44@r-forge.r-project.org> Author: chenyian Date: 2015-02-02 21:15:56 +0100 (Mon, 02 Feb 2015) New Revision: 3589 Modified: pkg/FactorAnalytics/R/fitTsfmTiming.r pkg/FactorAnalytics/man/fitTsfmTiming.Rd Log: update the example in fitTsfmTiming.Rd. Modified: pkg/FactorAnalytics/R/fitTsfmTiming.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmTiming.r 2015-02-01 19:50:19 UTC (rev 3588) +++ pkg/FactorAnalytics/R/fitTsfmTiming.r 2015-02-02 20:15:56 UTC (rev 3589) @@ -142,7 +142,7 @@ #' #' # example: Market-timing factors with robust fit #' fit <- fitTsfmTiming(asset.names=colnames(managers[,(1:6)]), factor.names=NULL, -#' mkt.name="SP500 TR", data=managers) +#' mkt.name="SP500 TR",rf.name="US 3m TR",data=managers) #' summary(fit) #' fitted(fit) #' Modified: pkg/FactorAnalytics/man/fitTsfmTiming.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfmTiming.Rd 2015-02-01 19:50:19 UTC (rev 3588) +++ pkg/FactorAnalytics/man/fitTsfmTiming.Rd 2015-02-02 20:15:56 UTC (rev 3589) @@ -131,7 +131,7 @@ # example: Market-timing factors with robust fit fit <- fitTsfmTiming(asset.names=colnames(managers[,(1:6)]), factor.names=NULL, - mkt.name="SP500 TR", data=managers) + mkt.name="SP500 TR",rf.name="US 3m TR",data=managers) summary(fit) fitted(fit) } From noreply at r-forge.r-project.org Tue Feb 3 03:13:27 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 3 Feb 2015 03:13:27 +0100 (CET) Subject: [Returnanalytics-commits] r3590 - in pkg/FactorAnalytics: . R data man Message-ID: <20150203021327.2EA93187904@r-forge.r-project.org> Author: chenyian Date: 2015-02-03 03:13:26 +0100 (Tue, 03 Feb 2015) New Revision: 3590 Added: pkg/FactorAnalytics/data/managers.RData Removed: pkg/FactorAnalytics/data/managers.rda Modified: pkg/FactorAnalytics/.Rbuildignore pkg/FactorAnalytics/DESCRIPTION pkg/FactorAnalytics/R/fitTsfm.R pkg/FactorAnalytics/R/fitTsfmTiming.r pkg/FactorAnalytics/R/fmCov.R pkg/FactorAnalytics/R/fmSdDecomp.R pkg/FactorAnalytics/R/paFm.r pkg/FactorAnalytics/R/plot.tsfm.r pkg/FactorAnalytics/R/predict.tsfm.r pkg/FactorAnalytics/R/print.pafm.r pkg/FactorAnalytics/R/print.tsfm.r pkg/FactorAnalytics/R/summary.pafm.r pkg/FactorAnalytics/R/summary.tsfm.r pkg/FactorAnalytics/man/fitTsfm.Rd pkg/FactorAnalytics/man/fitTsfmTiming.Rd pkg/FactorAnalytics/man/fmCov.Rd pkg/FactorAnalytics/man/fmSdDecomp.Rd pkg/FactorAnalytics/man/paFm.Rd pkg/FactorAnalytics/man/plot.tsfm.Rd pkg/FactorAnalytics/man/predict.tsfm.Rd pkg/FactorAnalytics/man/print.pafm.Rd pkg/FactorAnalytics/man/print.tsfm.Rd pkg/FactorAnalytics/man/summary.pafm.Rd pkg/FactorAnalytics/man/summary.tsfm.Rd Log: Modify the column names of managers.RData and related examples to accommodate the column name changes if merge.xts is used. Basically, the naming fashion is c("EDHEC.LS.EQ","SP500.TR","US.10Y.TR","US.3m.TR") rather than c("EDHEC LS EQ","SP500 TR","US 10Y TR","US 3m TR"). Modified: pkg/FactorAnalytics/.Rbuildignore =================================================================== --- pkg/FactorAnalytics/.Rbuildignore 2015-02-02 20:15:56 UTC (rev 3589) +++ pkg/FactorAnalytics/.Rbuildignore 2015-02-03 02:13:26 UTC (rev 3590) @@ -1,9 +1,2 @@ -^\.svn$ -^sandbox/*$ -^R/\.svn$ -^data/\.svn$ -^inst/\.svn$ -^man/\.svn$ -^vignettes/\.svn$ ^.*\.Rproj$ ^\.Rproj\.user$ Modified: pkg/FactorAnalytics/DESCRIPTION =================================================================== --- pkg/FactorAnalytics/DESCRIPTION 2015-02-02 20:15:56 UTC (rev 3589) +++ pkg/FactorAnalytics/DESCRIPTION 2015-02-03 02:13:26 UTC (rev 3590) @@ -1,36 +1,36 @@ -Package: factorAnalytics -Type: Package -Title: Factor Analytics -Version: 2.0.10 -Date: 2015-01-27 -Author: Eric Zivot, Sangeetha Srinivasan and Yi-An Chen -Maintainer: Sangeetha Srinivasan -Description: An R package for the estimation and risk analysis of linear factor - models for asset returns and portfolios. It contains model fitting methods - for the three major types of factor models: time series (or, macroeconomic) - factor model, fundamental factor model and statistical factor model. They - allow for different types of distributions to be specified for modeling the - fat-tailed behavior of financial returns, including Edgeworth expansions. - Risk analysis measures such as VaR and ES, as well as performance - attribution for factor models (factor-contributed vs idiosyncratic returns) - are included. -License: GPL-2 -Depends: - R (>= 3.0.0), - xts (>= 0.9) -Imports: - PerformanceAnalytics(>= 1.1.0), - corrplot, - robust, - leaps, - lars, - strucchange, - lmtest, - sandwich, - lattice, - MASS -Suggests: - testthat, quantmod, knitr -LazyLoad: yes -LazyDataCompression: xz -URL: http://r-forge.r-project.org/R/?group_id=579 +Package: factorAnalytics +Type: Package +Title: Factor Analytics +Version: 2.0.10 +Date: 2015-01-27 +Author: Eric Zivot, Sangeetha Srinivasan and Yi-An Chen +Maintainer: Sangeetha Srinivasan +Description: An R package for the estimation and risk analysis of linear factor + models for asset returns and portfolios. It contains model fitting methods + for the three major types of factor models: time series (or, macroeconomic) + factor model, fundamental factor model and statistical factor model. They + allow for different types of distributions to be specified for modeling the + fat-tailed behavior of financial returns, including Edgeworth expansions. + Risk analysis measures such as VaR and ES, as well as performance + attribution for factor models (factor-contributed vs idiosyncratic returns) + are included. +License: GPL-2 +Depends: + R (>= 3.0.0), + xts (>= 0.9) +Imports: + PerformanceAnalytics(>= 1.1.0), + corrplot, + robust, + leaps, + lars, + strucchange, + lmtest, + sandwich, + lattice, + MASS +Suggests: + testthat, quantmod, knitr +LazyLoad: yes +LazyDataCompression: xz +URL: http://r-forge.r-project.org/R/?group_id=579 Modified: pkg/FactorAnalytics/R/fitTsfm.R =================================================================== --- pkg/FactorAnalytics/R/fitTsfm.R 2015-02-02 20:15:56 UTC (rev 3589) +++ pkg/FactorAnalytics/R/fitTsfm.R 2015-02-03 02:13:26 UTC (rev 3590) @@ -155,10 +155,6 @@ #' # group plot; type selected from menu prompt; auto-looped for multiple plots #' # plot(fit) #' -#' # example: Market-timing factors with robust fit -#' fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), factor.names=NULL, -#' mkt.name="SP500 TR", mkt.timing="HM", data=managers, -#' fit.method="Robust") #' #' # example using "subsets" variable selection #' fit.sub <- fitTsfm(asset.names=colnames(managers[,(1:6)]), @@ -169,7 +165,7 @@ #' # example using "lars" variable selection and subtracting risk-free rate #' fit.lar <- fitTsfm(asset.names=colnames(managers[,(1:6)]), #' factor.names=colnames(managers[,(7:9)]), -#' rf.name="US 3m TR", data=managers, +#' rf.name="US.3m.TR", data=managers, #' variable.selection="lars", lars.criterion="cv") #' #' @importFrom PerformanceAnalytics checkData @@ -201,10 +197,10 @@ factor.names <- NULL } - if (xor(is.null(mkt.name), is.null(mkt.timing))) { - stop("Missing argument: Both mkt.name and mkt.timing are necessary to add - market timing factors") - } +# if (xor(is.null(mkt.name), is.null(mkt.timing))) { +# stop("Missing argument: Both mkt.name and mkt.timing are necessary to add +# market timing factors") +# } # extract arguments to pass to different fit and variable selection functions decay <- control$decay Modified: pkg/FactorAnalytics/R/fitTsfmTiming.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmTiming.r 2015-02-02 20:15:56 UTC (rev 3589) +++ pkg/FactorAnalytics/R/fitTsfmTiming.r 2015-02-03 02:13:26 UTC (rev 3590) @@ -105,7 +105,7 @@ #' Where N is the number of assets, K is the number of factors and T is the #' number of time periods. #' -#' @author Eric Zivot, Sangeetha Srinivasan and Yi-An Chen. +#' @author Yi-An Chen. #' #' @references #' Christopherson, J. A., Carino, D. R., & Ferson, W. E. (2009). Portfolio @@ -142,7 +142,7 @@ #' #' # example: Market-timing factors with robust fit #' fit <- fitTsfmTiming(asset.names=colnames(managers[,(1:6)]), factor.names=NULL, -#' mkt.name="SP500 TR",rf.name="US 3m TR",data=managers) +#' mkt.name="SP500.TR",rf.name="US.3m.TR",data=managers) #' summary(fit) #' fitted(fit) #' @@ -156,10 +156,13 @@ fitTsfmTiming <- function(asset.names, factor.names=NULL, mkt.name=NULL, rf.name=NULL, data=data, fit.method=c("OLS","DLS","Robust"), variable.selection=c("none","stepwise","subsets","lars"), control=fitTsfm.control(...),...) { + if (is.null(mkt.name)){ + stop("Missing argument: mkt.name has to be specified for market timing model.") + } factor.names <- union(factor.names,mkt.name) -fit.Timing <- fitTsfm(asset.names=asset.names,factor.names=factor.names,mkt.name=mkt.name,rf.name=rf.name, + fit.Timing <- fitTsfm(asset.names=asset.names,factor.names=factor.names,mkt.name=mkt.name,rf.name=rf.name, data=data,fit.method=fit.method,variable.selection=variable.selection,control=control,mkt.timing="HM") return(fit.Timing) Modified: pkg/FactorAnalytics/R/fmCov.R =================================================================== --- pkg/FactorAnalytics/R/fmCov.R 2015-02-02 20:15:56 UTC (rev 3589) +++ pkg/FactorAnalytics/R/fmCov.R 2015-02-03 02:13:26 UTC (rev 3590) @@ -1,128 +1,128 @@ -#' @title Covariance Matrix for assets' returns from fitted factor model. -#' -#' @description Computes the covariance matrix for assets' returns based on a -#' fitted factor model. This is a generic function with methods for classes -#' \code{tsfm}, \code{sfm} and \code{ffm}. -#' -#' @details \code{R(i, t)}, the return on asset \code{i} at time \code{t}, -#' is assumed to follow a factor model of the form, \cr \cr -#' \code{R(i,t) = alpha(i) + beta(i)*f(t) + e(i,t)}, \cr \cr -#' where, \code{alpha(i)} is the intercept, \code{f(t)} is a {K x 1} vector of -#' factor returns at time \code{t}, \code{beta(i)} is a \code{1 x K} vector of -#' factor exposures and the error terms \code{e(i,t)} are serially -#' uncorrelated across time and contemporaneously uncorrelated across assets -#' so that \code{e(i,t) ~ iid(0,sig(i)^2)}. Thus, the variance of asset -#' \code{i}'s return is given by \cr \cr -#' \code{var(R(i)) = beta(i)*cov(F)*tr(beta(i)) + sig(i)^2}. \cr \cr -#' And, the \code{N x N} covariance matrix of asset returns is \cr \cr -#' \code{var(R) = B*cov(F)*tr(B) + D}, \cr \cr -#' where, B is the \code{N x K} matrix of factor betas and \code{D} is a -#' diagonal matrix with \code{sig(i)^2} along the diagonal. -#' -#' The method for computing covariance can be specified via the \dots -#' argument. Note that the default of \code{use="pairwise.complete.obs"} for -#' handling NAs restricts the method to "pearson". -#' -#' @param object fit object of class \code{tsfm}, \code{sfm} or \code{ffm}. -#' @param use an optional character string giving a method for computing -#' covariances in the presence of missing values. This must be (an -#' abbreviation of) one of the strings "everything", "all.obs", -#' "complete.obs", "na.or.complete", or "pairwise.complete.obs". Default is -#' "pairwise.complete.obs". -#' @param ... optional arguments passed to \code{\link[stats]{cov}}. -#' -#' @return The computed \code{N x N} covariance matrix for asset returns based -#' on the fitted factor model. -#' -#' @author Eric Zivot, Yi-An Chen and Sangeetha Srinivasan. -#' -#' @references -#' Zivot, E., & Jia-hui, W. A. N. G. (2006). Modeling Financial Time -#' Series with S-Plus Springer-Verlag. -#' -#' @seealso \code{\link{fitTsfm}}, \code{\link{fitSfm}}, \code{\link{fitFfm}} -#' -#' \code{\link[stats]{cov}} for more details on arguments \code{use} and -#' \code{method}. -#' -#' @examples -#' # Time Series Factor model -#' data(managers) -#' fit <- fitTsfm(asset.names=colnames(managers[, (1:6)]), -#' factor.names=c("EDHEC LS EQ","SP500 TR"), data=managers) -#' fmCov(fit) -#' -#' # Statistical Factor Model -#' data(StockReturns) -#' sfm.pca.fit <- fitSfm(r.M, k=2) -#' fmCov(sfm.pca.fit) -#' -#' \dontrun{ -#' # Fundamental Factor Model -#' data(stock) -#' # there are 447 assets -#' exposure.names <- c("BOOK2MARKET", "LOG.MARKETCAP") -#' beta.mat <- subset(stock, DATE=="2003-12-31")[, exposure.names] -#' beta.mat1 <- cbind(rep(1, 447), beta.mat1) -#' # FM return covariance -#' fit.fund <- fitFfm(exposure.names=c("BOOK2MARKET", "LOG.MARKETCAP"), -#' data=stock, returnsvar="RETURN", datevar="DATE", -#' assetvar="TICKER", wls=TRUE, regression="classic", -#' covariance="classic", full.resid.cov=FALSE) -#' ret.cov.fundm <- fmCov(beta.mat1,fit.fund$factor.cov$cov,fit.fund$resid.sd) -#' fit.fund$returns.cov$cov == ret.cov.fundm -#' } -#' -#' @rdname fmCov -#' @export - -fmCov <- function(object, ...){ - # check input object validity - if (!inherits(object, c("tsfm", "sfm", "ffm"))) { - stop("Invalid argument: Object should be of class 'tsfm', 'sfm' or 'ffm'.") - } - UseMethod("fmCov") -} - -#' @rdname fmCov -#' @method fmCov tsfm -#' @export - -fmCov.tsfm <- function(object, use="pairwise.complete.obs", ...) { - - # get parameters and factors from factor model - beta <- as.matrix(object$beta) - # convert NAs to 0 to enable matrix multiplication - beta[is.na(beta)] <- 0 - sig2.e = object$resid.sd^2 - factor <- as.matrix(object$data[, object$factor.names]) - - # factor covariance matrix - factor.cov = cov(factor, use=use, ...) - - # residual covariance matrix D - if (length(sig2.e) > 1) { - D.e = diag(sig2.e) - } else { - D.e = as.vector(sig2.e) - } - - cov.fm = beta %*% factor.cov %*% t(beta) + D.e - - if (any(diag(chol(cov.fm))==0)) { - warning("Covariance matrix is not positive definite!") - } - - return(cov.fm) -} - -#' @rdname fmCov -#' @method fmCov sfm -#' @export - -fmCov.sfm <- function(object, use="pairwise.complete.obs", ...) { - - # already computed via fitSfm function - return(object$Omega) -} - +#' @title Covariance Matrix for assets' returns from fitted factor model. +#' +#' @description Computes the covariance matrix for assets' returns based on a +#' fitted factor model. This is a generic function with methods for classes +#' \code{tsfm}, \code{sfm} and \code{ffm}. +#' +#' @details \code{R(i, t)}, the return on asset \code{i} at time \code{t}, +#' is assumed to follow a factor model of the form, \cr \cr +#' \code{R(i,t) = alpha(i) + beta(i)*f(t) + e(i,t)}, \cr \cr +#' where, \code{alpha(i)} is the intercept, \code{f(t)} is a {K x 1} vector of +#' factor returns at time \code{t}, \code{beta(i)} is a \code{1 x K} vector of +#' factor exposures and the error terms \code{e(i,t)} are serially +#' uncorrelated across time and contemporaneously uncorrelated across assets +#' so that \code{e(i,t) ~ iid(0,sig(i)^2)}. Thus, the variance of asset +#' \code{i}'s return is given by \cr \cr +#' \code{var(R(i)) = beta(i)*cov(F)*tr(beta(i)) + sig(i)^2}. \cr \cr +#' And, the \code{N x N} covariance matrix of asset returns is \cr \cr +#' \code{var(R) = B*cov(F)*tr(B) + D}, \cr \cr +#' where, B is the \code{N x K} matrix of factor betas and \code{D} is a +#' diagonal matrix with \code{sig(i)^2} along the diagonal. +#' +#' The method for computing covariance can be specified via the \dots +#' argument. Note that the default of \code{use="pairwise.complete.obs"} for +#' handling NAs restricts the method to "pearson". +#' +#' @param object fit object of class \code{tsfm}, \code{sfm} or \code{ffm}. +#' @param use an optional character string giving a method for computing +#' covariances in the presence of missing values. This must be (an +#' abbreviation of) one of the strings "everything", "all.obs", +#' "complete.obs", "na.or.complete", or "pairwise.complete.obs". Default is +#' "pairwise.complete.obs". +#' @param ... optional arguments passed to \code{\link[stats]{cov}}. +#' +#' @return The computed \code{N x N} covariance matrix for asset returns based +#' on the fitted factor model. +#' +#' @author Eric Zivot, Yi-An Chen and Sangeetha Srinivasan. +#' +#' @references +#' Zivot, E., & Jia-hui, W. A. N. G. (2006). Modeling Financial Time +#' Series with S-Plus Springer-Verlag. +#' +#' @seealso \code{\link{fitTsfm}}, \code{\link{fitSfm}}, \code{\link{fitFfm}} +#' +#' \code{\link[stats]{cov}} for more details on arguments \code{use} and +#' \code{method}. +#' +#' @examples +#' # Time Series Factor model +#' data(managers) +#' fit <- fitTsfm(asset.names=colnames(managers[, (1:6)]), +#' factor.names=c("EDHEC.LS.EQ","SP500.TR"), data=managers) +#' fmCov(fit) +#' +#' # Statistical Factor Model +#' data(StockReturns) +#' sfm.pca.fit <- fitSfm(r.M, k=2) +#' fmCov(sfm.pca.fit) +#' +#' \dontrun{ +#' # Fundamental Factor Model +#' data(stock) +#' # there are 447 assets +#' exposure.names <- c("BOOK2MARKET", "LOG.MARKETCAP") +#' beta.mat <- subset(stock, DATE=="2003-12-31")[, exposure.names] +#' beta.mat1 <- cbind(rep(1, 447), beta.mat1) +#' # FM return covariance +#' fit.fund <- fitFfm(exposure.names=c("BOOK2MARKET", "LOG.MARKETCAP"), +#' data=stock, returnsvar="RETURN", datevar="DATE", +#' assetvar="TICKER", wls=TRUE, regression="classic", +#' covariance="classic", full.resid.cov=FALSE) +#' ret.cov.fundm <- fmCov(beta.mat1,fit.fund$factor.cov$cov,fit.fund$resid.sd) +#' fit.fund$returns.cov$cov == ret.cov.fundm +#' } +#' +#' @rdname fmCov +#' @export + +fmCov <- function(object, ...){ + # check input object validity + if (!inherits(object, c("tsfm", "sfm", "ffm"))) { + stop("Invalid argument: Object should be of class 'tsfm', 'sfm' or 'ffm'.") + } + UseMethod("fmCov") +} + +#' @rdname fmCov +#' @method fmCov tsfm +#' @export + +fmCov.tsfm <- function(object, use="pairwise.complete.obs", ...) { + + # get parameters and factors from factor model + beta <- as.matrix(object$beta) + # convert NAs to 0 to enable matrix multiplication + beta[is.na(beta)] <- 0 + sig2.e = object$resid.sd^2 + factor <- as.matrix(object$data[, object$factor.names]) + + # factor covariance matrix + factor.cov = cov(factor, use=use, ...) + + # residual covariance matrix D + if (length(sig2.e) > 1) { + D.e = diag(sig2.e) + } else { + D.e = as.vector(sig2.e) + } + + cov.fm = beta %*% factor.cov %*% t(beta) + D.e + + if (any(diag(chol(cov.fm))==0)) { + warning("Covariance matrix is not positive definite!") + } + + return(cov.fm) +} + +#' @rdname fmCov +#' @method fmCov sfm +#' @export + +fmCov.sfm <- function(object, use="pairwise.complete.obs", ...) { + + # already computed via fitSfm function + return(object$Omega) +} + Modified: pkg/FactorAnalytics/R/fmSdDecomp.R =================================================================== --- pkg/FactorAnalytics/R/fmSdDecomp.R 2015-02-02 20:15:56 UTC (rev 3589) +++ pkg/FactorAnalytics/R/fmSdDecomp.R 2015-02-03 02:13:26 UTC (rev 3590) @@ -1,167 +1,167 @@ -#' @title Decompose standard deviation into individual factor contributions -#' -#' @description Compute the factor contributions to standard deviation (SD) of -#' assets' returns based on Euler's theorem, given the fitted factor model. -#' -#' @details The factor model for an asset's return at time \code{t} has the -#' form \cr \cr \code{R(t) = beta'f(t) + e(t) = beta.star'f.star(t)} \cr \cr -#' where, \code{beta.star=(beta,sig.e)} and \code{f.star(t)=[f(t)',z(t)]'}. -#' \cr \cr By Euler's theorem, the standard deviation of the asset's return -#' is given as: \cr \cr -#' \code{Sd.fm = sum(cSd_k) = sum(beta.star_k*mSd_k)} \cr \cr -#' where, summation is across the \code{K} factors and the residual, -#' \code{cSd} and \code{mSd} are the component and marginal -#' contributions to \code{SD} respectively. Computing \code{Sd.fm} and -#' \code{mSd} is very straight forward. The formulas are given below and -#' details are in the references. The covariance term is approximated by the -#' sample covariance. \cr \cr -#' \code{Sd.fm = sqrt(beta.star''cov(F.star)beta.star)} \cr -#' \code{mSd = cov(F.star)beta.star / Sd.fm} -#' -#' @param object fit object of class \code{tsfm}, \code{sfm} or \code{ffm}. -#' @param use an optional character string giving a method for computing -#' covariances in the presence of missing values. This must be (an -#' abbreviation of) one of the strings "everything", "all.obs", -#' "complete.obs", "na.or.complete", or "pairwise.complete.obs". Default is -#' "pairwise.complete.obs". -#' @param ... optional arguments passed to \code{\link[stats]{cov}}. -#' -#' @return A list containing -#' \item{Sd.fm}{length-N vector of factor model SDs of N-asset returns.} -#' \item{mSd}{N x (K+1) matrix of marginal contributions to SD.} -#' \item{cSd}{N x (K+1) matrix of component contributions to SD.} -#' \item{pcSd}{N x (K+1) matrix of percentage component contributions to SD.} -#' Where, \code{K} is the number of factors and N is the number of assets. -#' -#' @author Eric Zivot, Sangeetha Srinivasan and Yi-An Chen -#' -#' @references -#' Hallerback (2003). Decomposing Portfolio Value-at-Risk: A General Analysis. -#' The Journal of Risk, 5(2), 1-18. -#' -#' Meucci, A. (2007). Risk contributions from generic user-defined factors. -#' RISK-LONDON-RISK MAGAZINE LIMITED-, 20(6), 84. -#' -#' Yamai, Y., & Yoshiba, T. (2002). Comparative analyses of expected shortfall -#' and value-at-risk: their estimation error, decomposition, and optimization. -#' Monetary and economic studies, 20(1), 87-121. -#' -#' @seealso \code{\link{fitTsfm}}, \code{\link{fitSfm}}, \code{\link{fitFfm}} -#' for the different factor model fitting functions. -#' -#' \code{\link{fmCov}} for factor model covariance. -#' \code{\link{fmVaRDecomp}} for factor model VaR decomposition. -#' \code{\link{fmEsDecomp}} for factor model ES decomposition. -#' -#' @examples -#' # Time Series Factor Model -#' data(managers) -#' fit.macro <- fitTsfm(asset.names=colnames(managers[,(1:6)]), -#' factor.names=colnames(managers[,(7:9)]), -#' rf.name="US 3m TR", data=managers) -#' decomp <- fmSdDecomp(fit.macro) -#' # get the percentage component contributions -#' decomp$pcSd -#' -#' # Statistical Factor Model -#' data(StockReturns) -#' sfm.pca.fit <- fitSfm(r.M, k=2) -#' decomp <- fmSdDecomp(sfm.pca.fit) -#' decomp$pcSd -#' -#' @export - -fmSdDecomp <- function(object, ...){ - # check input object validity - if (!inherits(object, c("tsfm", "sfm", "ffm"))) { - stop("Invalid argument: Object should be of class 'tsfm', 'sfm' or 'ffm'.") - } - UseMethod("fmSdDecomp") -} - -## Remarks: -## The factor model for asset i's return has the form -## R(i,t) = beta_i'F(t) + e(i,t) = beta.star_i'F.star(t) -## where beta.star_i = (beta_i, sig.e_i)' and F.star(t) = (F(t)', z(t))' - -## Standard deviation of the asset i's return -## sd.fm_i = sqrt(beta.star_i'Cov(F.star)beta.star_i) - -## By Euler's theorem -## sd.fm_i = sum(cSd_i(k)) = sum(beta.star_i(k)*mSd_i(k)) -## where the sum is across the K factors + 1 residual term - -#' @rdname fmSdDecomp -#' @method fmSdDecomp tsfm -#' @export - -fmSdDecomp.tsfm <- function(object, use="pairwise.complete.obs", ...) { - - # get beta.star: N x (K+1) - beta <- object$beta - beta[is.na(beta)] <- 0 - beta.star <- as.matrix(cbind(beta, object$resid.sd)) - colnames(beta.star)[dim(beta.star)[2]] <- "residual" - - # get cov(F): K x K - factor <- as.matrix(object$data[, object$factor.names]) - factor.cov = cov(factor, use=use, ...) - - # get cov(F.star): (K+1) x (K+1) - K <- ncol(object$beta) - factor.star.cov <- diag(K+1) - factor.star.cov[1:K, 1:K] <- factor.cov - colnames(factor.star.cov) <- c(colnames(factor.cov),"residuals") - rownames(factor.star.cov) <- c(colnames(factor.cov),"residuals") - - # compute factor model sd; a vector of length N - Sd.fm <- sqrt(rowSums(beta.star %*% factor.star.cov * beta.star)) - - # compute marginal, component and percentage contributions to sd - # each of these have dimensions: N x (K+1) - mSd <- (t(factor.star.cov %*% t(beta.star)))/Sd.fm - cSd <- mSd * beta.star - pcSd = 100* cSd/Sd.fm - - fm.sd.decomp <- list(Sd.fm=Sd.fm, mSd=mSd, cSd=cSd, pcSd=pcSd) - - return(fm.sd.decomp) -} - -#' @rdname fmSdDecomp -#' @method fmSdDecomp sfm -#' @export - -fmSdDecomp.sfm <- function(object, use="pairwise.complete.obs", ...) { - - # get beta.star: N x (K+1) - beta <- object$loadings - beta[is.na(beta)] <- 0 - beta.star <- as.matrix(cbind(beta, object$resid.sd)) - colnames(beta.star)[dim(beta.star)[2]] <- "residual" - - # get cov(F): K x K - factor <- as.matrix(object$factors) - factor.cov = cov(factor, use=use, ...) - - # get cov(F.star): (K+1) x (K+1) - K <- object$k - factor.star.cov <- diag(K+1) - factor.star.cov[1:K, 1:K] <- factor.cov - colnames(factor.star.cov) <- c(colnames(factor.cov),"residuals") - rownames(factor.star.cov) <- c(colnames(factor.cov),"residuals") - - # compute factor model sd; a vector of length N - Sd.fm <- sqrt(rowSums(beta.star %*% factor.star.cov * beta.star)) - - # compute marginal, component and percentage contributions to sd - # each of these have dimensions: N x (K+1) - mSd <- (t(factor.star.cov %*% t(beta.star)))/Sd.fm - cSd <- mSd * beta.star - pcSd = 100* cSd/Sd.fm - - fm.sd.decomp <- list(Sd.fm=Sd.fm, mSd=mSd, cSd=cSd, pcSd=pcSd) - - return(fm.sd.decomp) -} - +#' @title Decompose standard deviation into individual factor contributions +#' +#' @description Compute the factor contributions to standard deviation (SD) of +#' assets' returns based on Euler's theorem, given the fitted factor model. +#' +#' @details The factor model for an asset's return at time \code{t} has the +#' form \cr \cr \code{R(t) = beta'f(t) + e(t) = beta.star'f.star(t)} \cr \cr +#' where, \code{beta.star=(beta,sig.e)} and \code{f.star(t)=[f(t)',z(t)]'}. +#' \cr \cr By Euler's theorem, the standard deviation of the asset's return +#' is given as: \cr \cr +#' \code{Sd.fm = sum(cSd_k) = sum(beta.star_k*mSd_k)} \cr \cr +#' where, summation is across the \code{K} factors and the residual, +#' \code{cSd} and \code{mSd} are the component and marginal +#' contributions to \code{SD} respectively. Computing \code{Sd.fm} and +#' \code{mSd} is very straight forward. The formulas are given below and +#' details are in the references. The covariance term is approximated by the +#' sample covariance. \cr \cr +#' \code{Sd.fm = sqrt(beta.star''cov(F.star)beta.star)} \cr +#' \code{mSd = cov(F.star)beta.star / Sd.fm} +#' +#' @param object fit object of class \code{tsfm}, \code{sfm} or \code{ffm}. +#' @param use an optional character string giving a method for computing +#' covariances in the presence of missing values. This must be (an +#' abbreviation of) one of the strings "everything", "all.obs", +#' "complete.obs", "na.or.complete", or "pairwise.complete.obs". Default is +#' "pairwise.complete.obs". +#' @param ... optional arguments passed to \code{\link[stats]{cov}}. +#' +#' @return A list containing +#' \item{Sd.fm}{length-N vector of factor model SDs of N-asset returns.} +#' \item{mSd}{N x (K+1) matrix of marginal contributions to SD.} +#' \item{cSd}{N x (K+1) matrix of component contributions to SD.} +#' \item{pcSd}{N x (K+1) matrix of percentage component contributions to SD.} +#' Where, \code{K} is the number of factors and N is the number of assets. +#' +#' @author Eric Zivot, Sangeetha Srinivasan and Yi-An Chen +#' +#' @references +#' Hallerback (2003). Decomposing Portfolio Value-at-Risk: A General Analysis. +#' The Journal of Risk, 5(2), 1-18. +#' +#' Meucci, A. (2007). Risk contributions from generic user-defined factors. +#' RISK-LONDON-RISK MAGAZINE LIMITED-, 20(6), 84. +#' +#' Yamai, Y., & Yoshiba, T. (2002). Comparative analyses of expected shortfall +#' and value-at-risk: their estimation error, decomposition, and optimization. +#' Monetary and economic studies, 20(1), 87-121. +#' +#' @seealso \code{\link{fitTsfm}}, \code{\link{fitSfm}}, \code{\link{fitFfm}} +#' for the different factor model fitting functions. +#' +#' \code{\link{fmCov}} for factor model covariance. +#' \code{\link{fmVaRDecomp}} for factor model VaR decomposition. +#' \code{\link{fmEsDecomp}} for factor model ES decomposition. +#' +#' @examples +#' # Time Series Factor Model +#' data(managers) +#' fit.macro <- fitTsfm(asset.names=colnames(managers[,(1:6)]), +#' factor.names=colnames(managers[,(7:9)]), +#' rf.name="US.3m.TR", data=managers) +#' decomp <- fmSdDecomp(fit.macro) +#' # get the percentage component contributions +#' decomp$pcSd +#' +#' # Statistical Factor Model +#' data(StockReturns) +#' sfm.pca.fit <- fitSfm(r.M, k=2) +#' decomp <- fmSdDecomp(sfm.pca.fit) +#' decomp$pcSd +#' +#' @export + +fmSdDecomp <- function(object, ...){ + # check input object validity + if (!inherits(object, c("tsfm", "sfm", "ffm"))) { + stop("Invalid argument: Object should be of class 'tsfm', 'sfm' or 'ffm'.") + } + UseMethod("fmSdDecomp") +} + +## Remarks: +## The factor model for asset i's return has the form +## R(i,t) = beta_i'F(t) + e(i,t) = beta.star_i'F.star(t) +## where beta.star_i = (beta_i, sig.e_i)' and F.star(t) = (F(t)', z(t))' + +## Standard deviation of the asset i's return +## sd.fm_i = sqrt(beta.star_i'Cov(F.star)beta.star_i) + +## By Euler's theorem +## sd.fm_i = sum(cSd_i(k)) = sum(beta.star_i(k)*mSd_i(k)) +## where the sum is across the K factors + 1 residual term + +#' @rdname fmSdDecomp +#' @method fmSdDecomp tsfm +#' @export + +fmSdDecomp.tsfm <- function(object, use="pairwise.complete.obs", ...) { + + # get beta.star: N x (K+1) + beta <- object$beta + beta[is.na(beta)] <- 0 + beta.star <- as.matrix(cbind(beta, object$resid.sd)) + colnames(beta.star)[dim(beta.star)[2]] <- "residual" + + # get cov(F): K x K + factor <- as.matrix(object$data[, object$factor.names]) + factor.cov = cov(factor, use=use, ...) + + # get cov(F.star): (K+1) x (K+1) + K <- ncol(object$beta) + factor.star.cov <- diag(K+1) + factor.star.cov[1:K, 1:K] <- factor.cov + colnames(factor.star.cov) <- c(colnames(factor.cov),"residuals") + rownames(factor.star.cov) <- c(colnames(factor.cov),"residuals") + + # compute factor model sd; a vector of length N + Sd.fm <- sqrt(rowSums(beta.star %*% factor.star.cov * beta.star)) + + # compute marginal, component and percentage contributions to sd + # each of these have dimensions: N x (K+1) + mSd <- (t(factor.star.cov %*% t(beta.star)))/Sd.fm + cSd <- mSd * beta.star + pcSd = 100* cSd/Sd.fm + + fm.sd.decomp <- list(Sd.fm=Sd.fm, mSd=mSd, cSd=cSd, pcSd=pcSd) + + return(fm.sd.decomp) +} + +#' @rdname fmSdDecomp +#' @method fmSdDecomp sfm +#' @export + +fmSdDecomp.sfm <- function(object, use="pairwise.complete.obs", ...) { + + # get beta.star: N x (K+1) + beta <- object$loadings + beta[is.na(beta)] <- 0 + beta.star <- as.matrix(cbind(beta, object$resid.sd)) + colnames(beta.star)[dim(beta.star)[2]] <- "residual" + + # get cov(F): K x K + factor <- as.matrix(object$factors) + factor.cov = cov(factor, use=use, ...) + + # get cov(F.star): (K+1) x (K+1) + K <- object$k + factor.star.cov <- diag(K+1) + factor.star.cov[1:K, 1:K] <- factor.cov + colnames(factor.star.cov) <- c(colnames(factor.cov),"residuals") + rownames(factor.star.cov) <- c(colnames(factor.cov),"residuals") + + # compute factor model sd; a vector of length N + Sd.fm <- sqrt(rowSums(beta.star %*% factor.star.cov * beta.star)) + + # compute marginal, component and percentage contributions to sd + # each of these have dimensions: N x (K+1) + mSd <- (t(factor.star.cov %*% t(beta.star)))/Sd.fm + cSd <- mSd * beta.star + pcSd = 100* cSd/Sd.fm + + fm.sd.decomp <- list(Sd.fm=Sd.fm, mSd=mSd, cSd=cSd, pcSd=pcSd) + + return(fm.sd.decomp) +} + Modified: pkg/FactorAnalytics/R/paFm.r =================================================================== --- pkg/FactorAnalytics/R/paFm.r 2015-02-02 20:15:56 UTC (rev 3589) +++ pkg/FactorAnalytics/R/paFm.r 2015-02-03 02:13:26 UTC (rev 3590) @@ -1,239 +1,239 @@ -#' @title Compute cumulative mean attribution for factor models -#' -#' @description Decompose total returns into returns attributed to factors and -#' specific returns. An object of class \code{"pafm"} is generated, with -#' methods for generic functions \code{plot}, \code{summary} and \code{print}. -#' -#' @details Total returns can be decomposed into returns attributed to factors -#' and specific returns. \cr \eqn{R_t = \sum b_k * f_kt + u_t, t=1...T} \cr -#' \code{b_k} is exposure to factor k and \code{f_kt} is factor k's return at -#' time t. The return attributed to factor k is \code{b_k * f_kt} and specific -#' return is \code{u_t}. -#' -#' @param fit an object of class \code{tsfm}, \code{sfm} or \code{ffm}. -#' @param ... other arguments/controls passed to the fit methods. -#' -#' @return The returned object is of class \code{"pafm"} containing -#' \item{cum.ret.attr.f}{N X K matrix of cumulative return attributed to -#' factors.} -#' \item{cum.spec.ret}{length-N vector of cumulative specific returns.} -#' \item{attr.list}{list of time series of attributed returns for every -#' portfolio.} -#' -#' @author Yi-An Chen and Sangeetha Srinivasan -#' -#' @references Grinold, R. and Kahn, R. (1999) Active Portfolio Management: A -#' Quantitative Approach for Producing Superior Returns and Controlling Risk. -#' McGraw-Hill. -#' -#' @seealso \code{\link{fitTsfm}}, \code{\link{fitSfm}}, \code{\link{fitFfm}} -#' for the factor model fitting functions. -#' -#' The \code{pafm} methods for generic functions: -#' \code{\link{plot.pafm}}, \code{\link{print.pafm}} and -#' \code{\link{summary.pafm}}. -#' -#' @examples -#' data(managers) -#' fit <- fitTsfm(asset.names=colnames(managers[, (1:6)]), -#' factor.names=c("EDHEC LS EQ","SP500 TR"), data=managers) -#' # without benchmark -#' fm.attr <- paFm(fit) -#' -#' @importFrom PerformanceAnalytics Return.cumulative -#' -#' @export -#' - -paFm <- function(fit, ...) { - - # check input object validity - if (!inherits(fit, c("tsfm", "sfm", "ffm"))) { - stop("Invalid argument: fit should be of class 'tsfm', 'sfm' or 'ffm'.") - } - - # TSFM chunk - - if (class(fit)=="tsfm") { - - # return attributed to factors - cum.attr.ret <- fit$beta - cum.spec.ret <- fit$alpha - factorNames <- fit$factor.names - fundNames <- fit$asset.names - - attr.list <- list() - - for (k in fundNames) { - fit.lm <- fit$asset.fit[[k]] - - ## extract information from lm, lmRob or lars object - reg.xts <- na.omit(fit$data[, c(k, factorNames)]) - dates <- as.Date(index(reg.xts)) - actual.xts <- xts(fit.lm$model[1], dates) - # attributed returns - # active portfolio management p.512 17A.9 - # top-down method - - cum.ret <- Return.cumulative(actual.xts) - # setup initial value - attr.ret.xts.all <- xts(, dates) - - for ( i in factorNames ) { - - if (is.na(fit$beta[k, i])) { - cum.attr.ret[k, i] <- NA - attr.ret.xts.all <- merge(attr.ret.xts.all, - xts(rep(NA, length(date)), dates)) - } else { - attr.ret.xts <- actual.xts - - xts(as.matrix(fit.lm$model[i])%*%as.matrix(fit.lm$coef[i]), dates) - cum.attr.ret[k, i] <- cum.ret - - Return.cumulative(actual.xts-attr.ret.xts) - attr.ret.xts.all <- merge(attr.ret.xts.all, attr.ret.xts) - } - } - - # specific returns - spec.ret.xts <- actual.xts - [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3590 From noreply at r-forge.r-project.org Tue Feb 3 03:23:04 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 3 Feb 2015 03:23:04 +0100 (CET) Subject: [Returnanalytics-commits] r3591 - pkg/FactorAnalytics/data Message-ID: <20150203022304.5BD2C187904@r-forge.r-project.org> Author: chenyian Date: 2015-02-03 03:23:03 +0100 (Tue, 03 Feb 2015) New Revision: 3591 Removed: pkg/FactorAnalytics/data/managers.RData Log: Deleted: pkg/FactorAnalytics/data/managers.RData =================================================================== (Binary files differ) From noreply at r-forge.r-project.org Tue Feb 3 03:23:52 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 3 Feb 2015 03:23:52 +0100 (CET) Subject: [Returnanalytics-commits] r3592 - pkg/FactorAnalytics/data Message-ID: <20150203022352.E03A8187904@r-forge.r-project.org> Author: chenyian Date: 2015-02-03 03:23:52 +0100 (Tue, 03 Feb 2015) New Revision: 3592 Added: pkg/FactorAnalytics/data/managers.RData Log: reload the new managers.RData Added: pkg/FactorAnalytics/data/managers.RData =================================================================== (Binary files differ) Property changes on: pkg/FactorAnalytics/data/managers.RData ___________________________________________________________________ Added: svn:mime-type + application/octet-stream From noreply at r-forge.r-project.org Tue Feb 3 03:56:12 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 3 Feb 2015 03:56:12 +0100 (CET) Subject: [Returnanalytics-commits] r3593 - in pkg/FactorAnalytics: . R man Message-ID: <20150203025612.63656186E7E@r-forge.r-project.org> Author: chenyian Date: 2015-02-03 03:56:12 +0100 (Tue, 03 Feb 2015) New Revision: 3593 Added: pkg/FactorAnalytics/R/fitTsfmLagBeta.r pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd Modified: pkg/FactorAnalytics/NAMESPACE Log: Add a new function fitTsfmLagBeta.r to estimate lagged Betas time series factor model. Modified: pkg/FactorAnalytics/NAMESPACE =================================================================== --- pkg/FactorAnalytics/NAMESPACE 2015-02-03 02:23:52 UTC (rev 3592) +++ pkg/FactorAnalytics/NAMESPACE 2015-02-03 02:56:12 UTC (rev 3593) @@ -31,6 +31,7 @@ export(fitSfm) export(fitTsfm) export(fitTsfmTiming) +export(fitTsfmLagBeta) export(fmCov) export(fmEsDecomp) export(fmSdDecomp) Added: pkg/FactorAnalytics/R/fitTsfmLagBeta.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmLagBeta.r (rev 0) +++ pkg/FactorAnalytics/R/fitTsfmLagBeta.r 2015-02-03 02:56:12 UTC (rev 3593) @@ -0,0 +1,183 @@ +#' @title Fit a lagged Betas factor model using time series regression +#' +#' @description This is a wrapper function to fits a time series lagged Betas factor model for one +#' or more 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 compute excess returns. +#' +#' Estimation method "OLS" corresponds to ordinary least squares using +#' \code{\link[stats]{lm}}, "DLS" is discounted least squares (weighted least +#' squares with exponentially declining weights that sum to unity), and, +#' "Robust" is robust regression (using \code{\link[robust]{lmRob}}). +#' +#' If \code{variable.selection="none"}, uses all the factors and performs no +#' variable selection. Whereas, "stepwise" performs traditional stepwise +#' LS or Robust regression (using \code{\link[stats]{step}} or +#' \code{\link[robust]{step.lmRob}}), that starts from the initial set of +#' factors and adds/subtracts factors only if the regression fit, as measured +#' by the Bayesian Information Criterion (BIC) or Akaike Information Criterion +#' (AIC), improves. And, "subsets" enables subsets selection using +#' \code{\link[leaps]{regsubsets}}; chooses the best performing subset of any +#' given size or within a range of subset sizes. Different methods such as +#' exhaustive search (default), forward or backward stepwise, or sequential +#' replacement can be employed.See \code{\link{fitTsfm.control}} for more +#' details on the control arguments. +#' +#' \code{variable.selection="lars"} corresponds to least angle regression +#' using \code{\link[lars]{lars}} with variants "lasso" (default), "lar", +#' "stepwise" or "forward.stagewise". Note: If \code{variable.selection="lars"}, +#' \code{fit.method} will be ignored. +#' +#' Market timing accounts for +#' the price movement of the general stock market relative to fixed income +#' securities. It includes +#' $down.market = max(0, R_f-R_m)$ as a factor, following Henriksson & Merton +#' (1981). The coefficient of this down-market factor can be interpreted as the +#' number of "free" put options on the market provided by the manager's +#' market-timings kills. +#' +#' \subsection{Data Processing}{ +#' +#' Note about NAs: Before model fitting, incomplete cases are removed for +#' every asset (return data combined with respective factors' return data) +#' using \code{\link[stats]{na.omit}}. Otherwise, all observations in +#' \code{data} are included. +#' +#' Note about \code{asset.names} and \code{factor.names}: Spaces in column +#' names of \code{data} will be converted to periods as \code{fitTsfm} works +#' with \code{xts} objects internally and colnames won't be left as they are. +#' } +#' +#' @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 mkt.name name of the column for market excess returns (Rm-Rf); this +#' is necessary to add market timing factors. Default is NULL. +#' @param rf.name name of the column of risk free rate variable to calculate +#' excess returns for all assets (in \code{asset.names}) and factors (in +#' \code{factor.names}). Default is NULL, and no action is taken. +#' @param LagBeta A integer number to specify numbers of lags of Betas to +#' include in the model. The Default is 1. +#' @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{mkt.name} and \code{rf.name}. +#' @param fit.method the estimation method, one of "OLS", "DLS" or "Robust". +#' See details. Default is "OLS". +#' @param variable.selection the variable selection method, one of "none", +#' "stepwise","subsets","lars". See details. Default is "none". +#' \code{mkt.name} is required if any of these options are to be implemented. +#' @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}} +#' +#' @return fitTsfm returns an object of class \code{"tsfm"} for which +#' \code{print}, \code{plot}, \code{predict} and \code{summary} methods exist. +#' +#' The generic accessor functions \code{coef}, \code{fitted} and +#' \code{residuals} extract various useful features of the fit object. +#' Additionally, \code{fmCov} computes the covariance matrix for asset returns +#' based on the fitted factor model +#' +#' 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}{length-N vector of estimated alphas.} +#' \item{beta}{N x K matrix 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 +#' \code{variable.selection="lars"}} +#' \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 Yi-An Chen. +#' +#' @references +#' Christopherson, J. A., Carino, D. R., & Ferson, W. E. (2009). Portfolio +#' performance measurement and benchmarking. McGraw Hill Professional. +#' +#' Efron, B., Hastie, T., Johnstone, I., & Tibshirani, R. (2004). Least angle +#' regression. The Annals of statistics, 32(2), 407-499. +#' +#' Hastie, T., Tibshirani, R., Friedman, J., Hastie, T., Friedman, J., & +#' Tibshirani, R. (2009). The elements of statistical learning (Vol. 2, No. 1). +#' New York: Springer. +#' +#' Henriksson, R. D., & Merton, R. C. (1981). On market timing and investment +#' performance. II. Statistical procedures for evaluating forecasting skills. +#' Journal of business, 513-533. +#' +#' Treynor, J., & Mazuy, K. (1966). Can mutual funds outguess the market. +#' Harvard business review, 44(4), 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[stats]{fitted}}, \code{\link[stats]{residuals}}, +#' \code{\link{fmCov}}, \code{\link{fmSdDecomp}}, \code{\link{fmVaRDecomp}} +#' and \code{\link{fmEsDecomp}}. +#' +#' \code{\link{paFm}} for Performance Attribution. +#' +#' @examples +#' # load data from the database +#' data(managers) +#' +#' # example: Market-timing factors with robust fit +#' fit <- fitTsfmLagBeta(asset.names=colnames(managers[,(1:6)]), LagBeta=2, +#' mkt.name="SP500.TR",rf.name="US.3m.TR",data=managers) +#' summary(fit) +#' fitted(fit) +#' +#' @importFrom PerformanceAnalytics checkData +#' @importFrom robust lmRob step.lmRob +#' @importFrom leaps regsubsets +#' @importFrom lars lars cv.lars +#' +#' @export + +fitTsfmLagBeta <- function(asset.names, factor.names=NULL, mkt.name=NULL, rf.name=NULL, + data=data, fit.method=c("OLS","DLS","Robust"),LagBeta=1, + variable.selection=c("none","stepwise","subsets","lars"), control=fitTsfm.control(...),...) { + + if (is.null(mkt.name)) { + stop("Missing argument: mkt.name has to be specified for lag Beta model.") + } + + + if (as.integer(LagBeta) != LagBeta | LagBeta < 1 ) { + stop("Invalid argument: LagBeta must be an integer and no less than 1. The default is 1.") + } + + # Create market lag terms + mktlag <- lag(data[,mkt.name],k=seq(1:LagBeta)) + for (i in 1:LagBeta) { + colnames(mktlag)[i] <- paste("MktLag",i,sep="") + factor.names <- c(factor.names,paste("MktLag",i,sep="")) + } + data <- merge(data,mktlag) + + fit <- fitTsfm(asset.names=asset.names,factor.names=factor.names,mkt.name=mkt.name,rf.name=rf.name, + data=data,fit.method=fit.method,variable.selection=variable.selection,control=control) + + return(fit) +} \ No newline at end of file Added: pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd (rev 0) +++ pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd 2015-02-03 02:56:12 UTC (rev 3593) @@ -0,0 +1,174 @@ +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/fitTsfmLagBeta.r +\name{fitTsfmLagBeta} +\alias{fitTsfmLagBeta} +\title{Fit a lagged Betas factor model using time series regression} +\usage{ +fitTsfmLagBeta(asset.names, factor.names = NULL, mkt.name = NULL, + rf.name = NULL, data = data, fit.method = c("OLS", "DLS", "Robust"), + LagBeta = 1, variable.selection = c("none", "stepwise", "subsets", + "lars"), control = fitTsfm.control(...), ...) +} +\arguments{ +\item{asset.names}{vector containing names of assets, whose returns or +excess returns are the dependent variable.} + +\item{factor.names}{vector containing names of the macroeconomic factors.} + +\item{mkt.name}{name of the column for market excess returns (Rm-Rf); this +is necessary to add market timing factors. Default is NULL.} + +\item{rf.name}{name of the column of risk free rate variable to calculate +excess returns for all assets (in \code{asset.names}) and factors (in +\code{factor.names}). Default is NULL, and no action is taken.} + +\item{data}{vector, matrix, data.frame, xts, timeSeries or zoo object +containing column(s) named in \code{asset.names}, \code{factor.names} and +optionally, \code{mkt.name} and \code{rf.name}.} + +\item{fit.method}{the estimation method, one of "OLS", "DLS" or "Robust". +See details. Default is "OLS".} + +\item{LagBeta}{A integer number to specify numbers of lags of Betas to +include in the model. The Default is 1.} + +\item{variable.selection}{the variable selection method, one of "none", +"stepwise","subsets","lars". See details. Default is "none". +\code{mkt.name} is required if any of these options are to be implemented.} + +\item{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.} + +\item{...}{arguments passed to \code{\link{fitTsfm.control}}} +} +\value{ +fitTsfm returns an object of class \code{"tsfm"} for which +\code{print}, \code{plot}, \code{predict} and \code{summary} methods exist. + +The generic accessor functions \code{coef}, \code{fitted} and +\code{residuals} extract various useful features of the fit object. +Additionally, \code{fmCov} computes the covariance matrix for asset returns +based on the fitted factor model + +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}{length-N vector of estimated alphas.} +\item{beta}{N x K matrix 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 +\code{variable.selection="lars"}} +\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. +} +\description{ +This is a wrapper function to fits a time series lagged Betas factor model for one +or more 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 compute excess returns. + +Estimation method "OLS" corresponds to ordinary least squares using +\code{\link[stats]{lm}}, "DLS" is discounted least squares (weighted least +squares with exponentially declining weights that sum to unity), and, +"Robust" is robust regression (using \code{\link[robust]{lmRob}}). + +If \code{variable.selection="none"}, uses all the factors and performs no +variable selection. Whereas, "stepwise" performs traditional stepwise +LS or Robust regression (using \code{\link[stats]{step}} or +\code{\link[robust]{step.lmRob}}), that starts from the initial set of +factors and adds/subtracts factors only if the regression fit, as measured +by the Bayesian Information Criterion (BIC) or Akaike Information Criterion +(AIC), improves. And, "subsets" enables subsets selection using +\code{\link[leaps]{regsubsets}}; chooses the best performing subset of any +given size or within a range of subset sizes. Different methods such as +exhaustive search (default), forward or backward stepwise, or sequential +replacement can be employed.See \code{\link{fitTsfm.control}} for more +details on the control arguments. + +\code{variable.selection="lars"} corresponds to least angle regression +using \code{\link[lars]{lars}} with variants "lasso" (default), "lar", +"stepwise" or "forward.stagewise". Note: If \code{variable.selection="lars"}, +\code{fit.method} will be ignored. + +Market timing accounts for +the price movement of the general stock market relative to fixed income +securities. It includes +$down.market = max(0, R_f-R_m)$ as a factor, following Henriksson & Merton +(1981). The coefficient of this down-market factor can be interpreted as the +number of "free" put options on the market provided by the manager's +market-timings kills. + +\subsection{Data Processing}{ + +Note about NAs: Before model fitting, incomplete cases are removed for +every asset (return data combined with respective factors' return data) +using \code{\link[stats]{na.omit}}. Otherwise, all observations in +\code{data} are included. + +Note about \code{asset.names} and \code{factor.names}: Spaces in column +names of \code{data} will be converted to periods as \code{fitTsfm} works +with \code{xts} objects internally and colnames won't be left as they are. +} +} +\examples{ +# load data from the database +data(managers) + +# example: Market-timing factors with robust fit +fit <- fitTsfmLagBeta(asset.names=colnames(managers[,(1:6)]), LagBeta=2, + mkt.name="SP500.TR",rf.name="US.3m.TR",data=managers) +summary(fit) +fitted(fit) +} +\author{ +Yi-An Chen. +} +\references{ +Christopherson, J. A., Carino, D. R., & Ferson, W. E. (2009). Portfolio +performance measurement and benchmarking. McGraw Hill Professional. + +Efron, B., Hastie, T., Johnstone, I., & Tibshirani, R. (2004). Least angle +regression. The Annals of statistics, 32(2), 407-499. + +Hastie, T., Tibshirani, R., Friedman, J., Hastie, T., Friedman, J., & +Tibshirani, R. (2009). The elements of statistical learning (Vol. 2, No. 1). +New York: Springer. + +Henriksson, R. D., & Merton, R. C. (1981). On market timing and investment +performance. II. Statistical procedures for evaluating forecasting skills. +Journal of business, 513-533. + +Treynor, J., & Mazuy, K. (1966). Can mutual funds outguess the market. +Harvard business review, 44(4), 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[stats]{fitted}}, \code{\link[stats]{residuals}}, +\code{\link{fmCov}}, \code{\link{fmSdDecomp}}, \code{\link{fmVaRDecomp}} +and \code{\link{fmEsDecomp}}. + +\code{\link{paFm}} for Performance Attribution. +} + From noreply at r-forge.r-project.org Tue Feb 3 18:38:59 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 3 Feb 2015 18:38:59 +0100 (CET) Subject: [Returnanalytics-commits] r3594 - in pkg/FactorAnalytics: . R man Message-ID: <20150203173859.DBABE187869@r-forge.r-project.org> Author: chenyian Date: 2015-02-03 18:38:59 +0100 (Tue, 03 Feb 2015) New Revision: 3594 Added: pkg/FactorAnalytics/R/fitTsfmMT.r pkg/FactorAnalytics/man/fitTsfmMT.Rd Removed: pkg/FactorAnalytics/man/fitTsfmTiming.Rd Modified: pkg/FactorAnalytics/NAMESPACE pkg/FactorAnalytics/R/fitTsfmLagBeta.r pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd Log: change function name: use fitTsfmMT.r as market timing TS model. Modified: pkg/FactorAnalytics/NAMESPACE =================================================================== --- pkg/FactorAnalytics/NAMESPACE 2015-02-03 02:56:12 UTC (rev 3593) +++ pkg/FactorAnalytics/NAMESPACE 2015-02-03 17:38:59 UTC (rev 3594) @@ -30,7 +30,7 @@ export(dCornishFisher) export(fitSfm) export(fitTsfm) -export(fitTsfmTiming) +export(fitTsfmMT) export(fitTsfmLagBeta) export(fmCov) export(fmEsDecomp) Modified: pkg/FactorAnalytics/R/fitTsfmLagBeta.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmLagBeta.r 2015-02-03 02:56:12 UTC (rev 3593) +++ pkg/FactorAnalytics/R/fitTsfmLagBeta.r 2015-02-03 17:38:59 UTC (rev 3594) @@ -143,8 +143,9 @@ #' data(managers) #' #' # example: Market-timing factors with robust fit -#' fit <- fitTsfmLagBeta(asset.names=colnames(managers[,(1:6)]), LagBeta=2, -#' mkt.name="SP500.TR",rf.name="US.3m.TR",data=managers) +#' fit <- fitTsfmLagBeta(asset.names=colnames(managers[,(1:6)]),LagBeta=2, +#' factor.names="SP500.TR",mkt.name="SP500.TR", +#' rf.name="US.3m.TR",data=managers) #' summary(fit) #' fitted(fit) #' Added: pkg/FactorAnalytics/R/fitTsfmMT.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmMT.r (rev 0) +++ pkg/FactorAnalytics/R/fitTsfmMT.r 2015-02-03 17:38:59 UTC (rev 3594) @@ -0,0 +1,169 @@ +#' @title Fit a time serie market timing factor model using time series regression +#' +#' @description This is a wrapper function to fits a time series market timing factor model for one +#' or more 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 compute excess returns. +#' +#' Estimation method "OLS" corresponds to ordinary least squares using +#' \code{\link[stats]{lm}}, "DLS" is discounted least squares (weighted least +#' squares with exponentially declining weights that sum to unity), and, +#' "Robust" is robust regression (using \code{\link[robust]{lmRob}}). +#' +#' If \code{variable.selection="none"}, uses all the factors and performs no +#' variable selection. Whereas, "stepwise" performs traditional stepwise +#' LS or Robust regression (using \code{\link[stats]{step}} or +#' \code{\link[robust]{step.lmRob}}), that starts from the initial set of +#' factors and adds/subtracts factors only if the regression fit, as measured +#' by the Bayesian Information Criterion (BIC) or Akaike Information Criterion +#' (AIC), improves. And, "subsets" enables subsets selection using +#' \code{\link[leaps]{regsubsets}}; chooses the best performing subset of any +#' given size or within a range of subset sizes. Different methods such as +#' exhaustive search (default), forward or backward stepwise, or sequential +#' replacement can be employed.See \code{\link{fitTsfm.control}} for more +#' details on the control arguments. +#' +#' \code{variable.selection="lars"} corresponds to least angle regression +#' using \code{\link[lars]{lars}} with variants "lasso" (default), "lar", +#' "stepwise" or "forward.stagewise". Note: If \code{variable.selection="lars"}, +#' \code{fit.method} will be ignored. +#' +#' Market timing accounts for +#' the price movement of the general stock market relative to fixed income +#' securities. It includes +#' $down.market = max(0, R_f-R_m)$ as a factor, following Henriksson & Merton +#' (1981). The coefficient of this down-market factor can be interpreted as the +#' number of "free" put options on the market provided by the manager's +#' market-timings kills. +#' +#' \subsection{Data Processing}{ +#' +#' Note about NAs: Before model fitting, incomplete cases are removed for +#' every asset (return data combined with respective factors' return data) +#' using \code{\link[stats]{na.omit}}. Otherwise, all observations in +#' \code{data} are included. +#' +#' Note about \code{asset.names} and \code{factor.names}: Spaces in column +#' names of \code{data} will be converted to periods as \code{fitTsfm} works +#' with \code{xts} objects internally and colnames won't be left as they are. +#' } +#' +#' @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 mkt.name name of the column for market excess returns (Rm-Rf); this +#' is necessary to add market timing factors. Default is NULL. +#' @param rf.name name of the column of risk free rate variable to calculate +#' excess returns for all assets (in \code{asset.names}) and factors (in +#' \code{factor.names}). Default is NULL, and no action is taken. +#' @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{mkt.name} and \code{rf.name}. +#' @param fit.method the estimation method, one of "OLS", "DLS" or "Robust". +#' See details. Default is "OLS". +#' @param variable.selection the variable selection method, one of "none", +#' "stepwise","subsets","lars". See details. Default is "none". +#' \code{mkt.name} is required if any of these options are to be implemented. +#' @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}} +#' +#' @return fitTsfm returns an object of class \code{"tsfm"} for which +#' \code{print}, \code{plot}, \code{predict} and \code{summary} methods exist. +#' +#' The generic accessor functions \code{coef}, \code{fitted} and +#' \code{residuals} extract various useful features of the fit object. +#' Additionally, \code{fmCov} computes the covariance matrix for asset returns +#' based on the fitted factor model +#' +#' 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}{length-N vector of estimated alphas.} +#' \item{beta}{N x K matrix 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 +#' \code{variable.selection="lars"}} +#' \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 Yi-An Chen. +#' +#' @references +#' Christopherson, J. A., Carino, D. R., & Ferson, W. E. (2009). Portfolio +#' performance measurement and benchmarking. McGraw Hill Professional. +#' +#' Efron, B., Hastie, T., Johnstone, I., & Tibshirani, R. (2004). Least angle +#' regression. The Annals of statistics, 32(2), 407-499. +#' +#' Hastie, T., Tibshirani, R., Friedman, J., Hastie, T., Friedman, J., & +#' Tibshirani, R. (2009). The elements of statistical learning (Vol. 2, No. 1). +#' New York: Springer. +#' +#' Henriksson, R. D., & Merton, R. C. (1981). On market timing and investment +#' performance. II. Statistical procedures for evaluating forecasting skills. +#' Journal of business, 513-533. +#' +#' Treynor, J., & Mazuy, K. (1966). Can mutual funds outguess the market. +#' Harvard business review, 44(4), 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[stats]{fitted}}, \code{\link[stats]{residuals}}, +#' \code{\link{fmCov}}, \code{\link{fmSdDecomp}}, \code{\link{fmVaRDecomp}} +#' and \code{\link{fmEsDecomp}}. +#' +#' \code{\link{paFm}} for Performance Attribution. +#' +#' @examples +#' # load data from the database +#' data(managers) +#' +#' # example: Market-timing factors with robust fit +#' fit <- fitTsfmMT(asset.names=colnames(managers[,(1:6)]), factor.names=NULL, +#' mkt.name="SP500.TR",rf.name="US.3m.TR",data=managers) +#' summary(fit) +#' fitted(fit) +#' +#' @importFrom PerformanceAnalytics checkData +#' @importFrom robust lmRob step.lmRob +#' @importFrom leaps regsubsets +#' @importFrom lars lars cv.lars +#' +#' @export + +fitTsfmMT <- function(asset.names, factor.names=NULL, mkt.name=NULL, rf.name=NULL, + data=data, fit.method=c("OLS","DLS","Robust"), + variable.selection=c("none","stepwise","subsets","lars"), control=fitTsfm.control(...),...) { + if (is.null(mkt.name)){ + stop("Missing argument: mkt.name has to be specified for market timing model.") + } + + factor.names <- union(factor.names,mkt.name) + + fit.Timing <- fitTsfm(asset.names=asset.names,factor.names=factor.names,mkt.name=mkt.name,rf.name=rf.name, + data=data,fit.method=fit.method,variable.selection=variable.selection,control=control,mkt.timing="HM") + +return(fit.Timing) +} Modified: pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd 2015-02-03 02:56:12 UTC (rev 3593) +++ pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd 2015-02-03 17:38:59 UTC (rev 3594) @@ -133,8 +133,9 @@ data(managers) # example: Market-timing factors with robust fit -fit <- fitTsfmLagBeta(asset.names=colnames(managers[,(1:6)]), LagBeta=2, - mkt.name="SP500.TR",rf.name="US.3m.TR",data=managers) +fit <- fitTsfmLagBeta(asset.names=colnames(managers[,(1:6)]),LagBeta=2, + factor.names="SP500.TR",mkt.name="SP500.TR", + rf.name="US.3m.TR",data=managers) summary(fit) fitted(fit) } Added: pkg/FactorAnalytics/man/fitTsfmMT.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfmMT.Rd (rev 0) +++ pkg/FactorAnalytics/man/fitTsfmMT.Rd 2015-02-03 17:38:59 UTC (rev 3594) @@ -0,0 +1,171 @@ +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/fitTsfmMT.r +\name{fitTsfmMT} +\alias{fitTsfmMT} +\title{Fit a time serie market timing factor model using time series regression} +\usage{ +fitTsfmMT(asset.names, factor.names = NULL, mkt.name = NULL, + rf.name = NULL, data = data, fit.method = c("OLS", "DLS", "Robust"), + variable.selection = c("none", "stepwise", "subsets", "lars"), + control = fitTsfm.control(...), ...) +} +\arguments{ +\item{asset.names}{vector containing names of assets, whose returns or +excess returns are the dependent variable.} + +\item{factor.names}{vector containing names of the macroeconomic factors.} + +\item{mkt.name}{name of the column for market excess returns (Rm-Rf); this +is necessary to add market timing factors. Default is NULL.} + +\item{rf.name}{name of the column of risk free rate variable to calculate +excess returns for all assets (in \code{asset.names}) and factors (in +\code{factor.names}). Default is NULL, and no action is taken.} + +\item{data}{vector, matrix, data.frame, xts, timeSeries or zoo object +containing column(s) named in \code{asset.names}, \code{factor.names} and +optionally, \code{mkt.name} and \code{rf.name}.} + +\item{fit.method}{the estimation method, one of "OLS", "DLS" or "Robust". +See details. Default is "OLS".} + +\item{variable.selection}{the variable selection method, one of "none", +"stepwise","subsets","lars". See details. Default is "none". +\code{mkt.name} is required if any of these options are to be implemented.} + +\item{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.} + +\item{...}{arguments passed to \code{\link{fitTsfm.control}}} +} +\value{ +fitTsfm returns an object of class \code{"tsfm"} for which +\code{print}, \code{plot}, \code{predict} and \code{summary} methods exist. + +The generic accessor functions \code{coef}, \code{fitted} and +\code{residuals} extract various useful features of the fit object. +Additionally, \code{fmCov} computes the covariance matrix for asset returns +based on the fitted factor model + +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}{length-N vector of estimated alphas.} +\item{beta}{N x K matrix 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 +\code{variable.selection="lars"}} +\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. +} +\description{ +This is a wrapper function to fits a time series market timing factor model for one +or more 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 compute excess returns. + +Estimation method "OLS" corresponds to ordinary least squares using +\code{\link[stats]{lm}}, "DLS" is discounted least squares (weighted least +squares with exponentially declining weights that sum to unity), and, +"Robust" is robust regression (using \code{\link[robust]{lmRob}}). + +If \code{variable.selection="none"}, uses all the factors and performs no +variable selection. Whereas, "stepwise" performs traditional stepwise +LS or Robust regression (using \code{\link[stats]{step}} or +\code{\link[robust]{step.lmRob}}), that starts from the initial set of +factors and adds/subtracts factors only if the regression fit, as measured +by the Bayesian Information Criterion (BIC) or Akaike Information Criterion +(AIC), improves. And, "subsets" enables subsets selection using +\code{\link[leaps]{regsubsets}}; chooses the best performing subset of any +given size or within a range of subset sizes. Different methods such as +exhaustive search (default), forward or backward stepwise, or sequential +replacement can be employed.See \code{\link{fitTsfm.control}} for more +details on the control arguments. + +\code{variable.selection="lars"} corresponds to least angle regression +using \code{\link[lars]{lars}} with variants "lasso" (default), "lar", +"stepwise" or "forward.stagewise". Note: If \code{variable.selection="lars"}, +\code{fit.method} will be ignored. + +Market timing accounts for +the price movement of the general stock market relative to fixed income +securities. It includes +$down.market = max(0, R_f-R_m)$ as a factor, following Henriksson & Merton +(1981). The coefficient of this down-market factor can be interpreted as the +number of "free" put options on the market provided by the manager's +market-timings kills. + +\subsection{Data Processing}{ + +Note about NAs: Before model fitting, incomplete cases are removed for +every asset (return data combined with respective factors' return data) +using \code{\link[stats]{na.omit}}. Otherwise, all observations in +\code{data} are included. + +Note about \code{asset.names} and \code{factor.names}: Spaces in column +names of \code{data} will be converted to periods as \code{fitTsfm} works +with \code{xts} objects internally and colnames won't be left as they are. +} +} +\examples{ +# load data from the database +data(managers) + +# example: Market-timing factors with robust fit +fit <- fitTsfmMT(asset.names=colnames(managers[,(1:6)]), factor.names=NULL, + mkt.name="SP500.TR",rf.name="US.3m.TR",data=managers) +summary(fit) +fitted(fit) +} +\author{ +Yi-An Chen. +} +\references{ +Christopherson, J. A., Carino, D. R., & Ferson, W. E. (2009). Portfolio +performance measurement and benchmarking. McGraw Hill Professional. + +Efron, B., Hastie, T., Johnstone, I., & Tibshirani, R. (2004). Least angle +regression. The Annals of statistics, 32(2), 407-499. + +Hastie, T., Tibshirani, R., Friedman, J., Hastie, T., Friedman, J., & +Tibshirani, R. (2009). The elements of statistical learning (Vol. 2, No. 1). +New York: Springer. + +Henriksson, R. D., & Merton, R. C. (1981). On market timing and investment +performance. II. Statistical procedures for evaluating forecasting skills. +Journal of business, 513-533. + +Treynor, J., & Mazuy, K. (1966). Can mutual funds outguess the market. +Harvard business review, 44(4), 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[stats]{fitted}}, \code{\link[stats]{residuals}}, +\code{\link{fmCov}}, \code{\link{fmSdDecomp}}, \code{\link{fmVaRDecomp}} +and \code{\link{fmEsDecomp}}. + +\code{\link{paFm}} for Performance Attribution. +} + Deleted: pkg/FactorAnalytics/man/fitTsfmTiming.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfmTiming.Rd 2015-02-03 02:56:12 UTC (rev 3593) +++ pkg/FactorAnalytics/man/fitTsfmTiming.Rd 2015-02-03 17:38:59 UTC (rev 3594) @@ -1,171 +0,0 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/fitTsfmTiming.r -\name{fitTsfmTiming} -\alias{fitTsfmTiming} -\title{Fit a time serie market timing factor model using time series regression} -\usage{ -fitTsfmTiming(asset.names, factor.names = NULL, mkt.name = NULL, - rf.name = NULL, data = data, fit.method = c("OLS", "DLS", "Robust"), - variable.selection = c("none", "stepwise", "subsets", "lars"), - control = fitTsfm.control(...), ...) -} -\arguments{ -\item{asset.names}{vector containing names of assets, whose returns or -excess returns are the dependent variable.} - -\item{factor.names}{vector containing names of the macroeconomic factors.} - -\item{mkt.name}{name of the column for market excess returns (Rm-Rf); this -is necessary to add market timing factors. Default is NULL.} - -\item{rf.name}{name of the column of risk free rate variable to calculate -excess returns for all assets (in \code{asset.names}) and factors (in -\code{factor.names}). Default is NULL, and no action is taken.} - -\item{data}{vector, matrix, data.frame, xts, timeSeries or zoo object -containing column(s) named in \code{asset.names}, \code{factor.names} and -optionally, \code{mkt.name} and \code{rf.name}.} - -\item{fit.method}{the estimation method, one of "OLS", "DLS" or "Robust". -See details. Default is "OLS".} - -\item{variable.selection}{the variable selection method, one of "none", -"stepwise","subsets","lars". See details. Default is "none". -\code{mkt.name} is required if any of these options are to be implemented.} - -\item{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.} - -\item{...}{arguments passed to \code{\link{fitTsfm.control}}} -} -\value{ -fitTsfm returns an object of class \code{"tsfm"} for which -\code{print}, \code{plot}, \code{predict} and \code{summary} methods exist. - -The generic accessor functions \code{coef}, \code{fitted} and -\code{residuals} extract various useful features of the fit object. -Additionally, \code{fmCov} computes the covariance matrix for asset returns -based on the fitted factor model - -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}{length-N vector of estimated alphas.} -\item{beta}{N x K matrix 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 -\code{variable.selection="lars"}} -\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. -} -\description{ -This is a wrapper function to fits a time series market timing factor model for one -or more 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 compute excess returns. - -Estimation method "OLS" corresponds to ordinary least squares using -\code{\link[stats]{lm}}, "DLS" is discounted least squares (weighted least -squares with exponentially declining weights that sum to unity), and, -"Robust" is robust regression (using \code{\link[robust]{lmRob}}). - -If \code{variable.selection="none"}, uses all the factors and performs no -variable selection. Whereas, "stepwise" performs traditional stepwise -LS or Robust regression (using \code{\link[stats]{step}} or -\code{\link[robust]{step.lmRob}}), that starts from the initial set of -factors and adds/subtracts factors only if the regression fit, as measured -by the Bayesian Information Criterion (BIC) or Akaike Information Criterion -(AIC), improves. And, "subsets" enables subsets selection using -\code{\link[leaps]{regsubsets}}; chooses the best performing subset of any -given size or within a range of subset sizes. Different methods such as -exhaustive search (default), forward or backward stepwise, or sequential -replacement can be employed.See \code{\link{fitTsfm.control}} for more -details on the control arguments. - -\code{variable.selection="lars"} corresponds to least angle regression -using \code{\link[lars]{lars}} with variants "lasso" (default), "lar", -"stepwise" or "forward.stagewise". Note: If \code{variable.selection="lars"}, -\code{fit.method} will be ignored. - -Market timing accounts for -the price movement of the general stock market relative to fixed income -securities. It includes -$down.market = max(0, R_f-R_m)$ as a factor, following Henriksson & Merton -(1981). The coefficient of this down-market factor can be interpreted as the -number of "free" put options on the market provided by the manager's -market-timings kills. - -\subsection{Data Processing}{ - -Note about NAs: Before model fitting, incomplete cases are removed for -every asset (return data combined with respective factors' return data) -using \code{\link[stats]{na.omit}}. Otherwise, all observations in -\code{data} are included. - -Note about \code{asset.names} and \code{factor.names}: Spaces in column -names of \code{data} will be converted to periods as \code{fitTsfm} works -with \code{xts} objects internally and colnames won't be left as they are. -} -} -\examples{ -# load data from the database -data(managers) - -# example: Market-timing factors with robust fit -fit <- fitTsfmTiming(asset.names=colnames(managers[,(1:6)]), factor.names=NULL, - mkt.name="SP500.TR",rf.name="US.3m.TR",data=managers) -summary(fit) -fitted(fit) -} -\author{ -Yi-An Chen. -} -\references{ -Christopherson, J. A., Carino, D. R., & Ferson, W. E. (2009). Portfolio -performance measurement and benchmarking. McGraw Hill Professional. - -Efron, B., Hastie, T., Johnstone, I., & Tibshirani, R. (2004). Least angle -regression. The Annals of statistics, 32(2), 407-499. - -Hastie, T., Tibshirani, R., Friedman, J., Hastie, T., Friedman, J., & -Tibshirani, R. (2009). The elements of statistical learning (Vol. 2, No. 1). -New York: Springer. - -Henriksson, R. D., & Merton, R. C. (1981). On market timing and investment -performance. II. Statistical procedures for evaluating forecasting skills. -Journal of business, 513-533. - -Treynor, J., & Mazuy, K. (1966). Can mutual funds outguess the market. -Harvard business review, 44(4), 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[stats]{fitted}}, \code{\link[stats]{residuals}}, -\code{\link{fmCov}}, \code{\link{fmSdDecomp}}, \code{\link{fmVaRDecomp}} -and \code{\link{fmEsDecomp}}. - -\code{\link{paFm}} for Performance Attribution. -} - From noreply at r-forge.r-project.org Wed Feb 4 01:26:42 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 4 Feb 2015 01:26:42 +0100 (CET) Subject: [Returnanalytics-commits] r3595 - in pkg/FactorAnalytics: R man Message-ID: <20150204002642.E15B41876D9@r-forge.r-project.org> Author: chenyian Date: 2015-02-04 01:26:42 +0100 (Wed, 04 Feb 2015) New Revision: 3595 Modified: pkg/FactorAnalytics/R/fitTsfm.R pkg/FactorAnalytics/R/fitTsfmLagBeta.r pkg/FactorAnalytics/R/fitTsfmMT.r pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd pkg/FactorAnalytics/man/fitTsfmMT.Rd Log: Typos check. Modified: pkg/FactorAnalytics/R/fitTsfm.R =================================================================== --- pkg/FactorAnalytics/R/fitTsfm.R 2015-02-03 17:38:59 UTC (rev 3594) +++ pkg/FactorAnalytics/R/fitTsfm.R 2015-02-04 00:26:42 UTC (rev 3595) @@ -196,7 +196,7 @@ if (missing(factor.names) && !is.null(mkt.name)) { factor.names <- NULL } - + # if (xor(is.null(mkt.name), is.null(mkt.timing))) { # stop("Missing argument: Both mkt.name and mkt.timing are necessary to add # market timing factors") @@ -244,7 +244,7 @@ # opt add mkt-timing factors: down.market=max(0,Rf-Rm), market.sqd=(Rm-Rf)^2 if("HM" %in% mkt.timing) { - down.market <- data.xts[,mkt.name] + down.market <- dat.xts[,mkt.name] down.market[down.market < 0 ] <- 0 dat.xts <- merge.xts(dat.xts,down.market) colnames(dat.xts)[dim(dat.xts)[2]] <- "down.market" Modified: pkg/FactorAnalytics/R/fitTsfmLagBeta.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmLagBeta.r 2015-02-03 17:38:59 UTC (rev 3594) +++ pkg/FactorAnalytics/R/fitTsfmLagBeta.r 2015-02-04 00:26:42 UTC (rev 3595) @@ -142,7 +142,7 @@ #' # load data from the database #' data(managers) #' -#' # example: Market-timing factors with robust fit +#' # example: Market-timing factors with OLS fit #' fit <- fitTsfmLagBeta(asset.names=colnames(managers[,(1:6)]),LagBeta=2, #' factor.names="SP500.TR",mkt.name="SP500.TR", #' rf.name="US.3m.TR",data=managers) @@ -161,7 +161,7 @@ variable.selection=c("none","stepwise","subsets","lars"), control=fitTsfm.control(...),...) { if (is.null(mkt.name)) { - stop("Missing argument: mkt.name has to be specified for lag Beta model.") + stop("Missing argument: mkt.name has to be specified for lagged Betas model.") } Modified: pkg/FactorAnalytics/R/fitTsfmMT.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmMT.r 2015-02-03 17:38:59 UTC (rev 3594) +++ pkg/FactorAnalytics/R/fitTsfmMT.r 2015-02-04 00:26:42 UTC (rev 3595) @@ -140,8 +140,8 @@ #' # load data from the database #' data(managers) #' -#' # example: Market-timing factors with robust fit -#' fit <- fitTsfmMT(asset.names=colnames(managers[,(1:6)]), factor.names=NULL, +#' # example: Market-timing factors with OLS fit +#' fit <- fitTsfmMT(asset.names=colnames(managers[,(1:6)]), #' mkt.name="SP500.TR",rf.name="US.3m.TR",data=managers) #' summary(fit) #' fitted(fit) Modified: pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd 2015-02-03 17:38:59 UTC (rev 3594) +++ pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd 2015-02-04 00:26:42 UTC (rev 3595) @@ -132,7 +132,7 @@ # load data from the database data(managers) -# example: Market-timing factors with robust fit +# example: Market-timing factors with OLS fit fit <- fitTsfmLagBeta(asset.names=colnames(managers[,(1:6)]),LagBeta=2, factor.names="SP500.TR",mkt.name="SP500.TR", rf.name="US.3m.TR",data=managers) Modified: pkg/FactorAnalytics/man/fitTsfmMT.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfmMT.Rd 2015-02-03 17:38:59 UTC (rev 3594) +++ pkg/FactorAnalytics/man/fitTsfmMT.Rd 2015-02-04 00:26:42 UTC (rev 3595) @@ -129,8 +129,8 @@ # load data from the database data(managers) -# example: Market-timing factors with robust fit -fit <- fitTsfmMT(asset.names=colnames(managers[,(1:6)]), factor.names=NULL, +# example: Market-timing factors with OLS fit +fit <- fitTsfmMT(asset.names=colnames(managers[,(1:6)]), mkt.name="SP500.TR",rf.name="US.3m.TR",data=managers) summary(fit) fitted(fit) From noreply at r-forge.r-project.org Wed Feb 4 01:29:05 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 4 Feb 2015 01:29:05 +0100 (CET) Subject: [Returnanalytics-commits] r3596 - pkg/FactorAnalytics/R Message-ID: <20150204002905.CA0451876D9@r-forge.r-project.org> Author: chenyian Date: 2015-02-04 01:29:05 +0100 (Wed, 04 Feb 2015) New Revision: 3596 Removed: pkg/FactorAnalytics/R/fitTsfmTiming.r Log: delete fitTsfmTiming.r. Deleted: pkg/FactorAnalytics/R/fitTsfmTiming.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmTiming.r 2015-02-04 00:26:42 UTC (rev 3595) +++ pkg/FactorAnalytics/R/fitTsfmTiming.r 2015-02-04 00:29:05 UTC (rev 3596) @@ -1,169 +0,0 @@ -#' @title Fit a time serie market timing factor model using time series regression -#' -#' @description This is a wrapper function to fits a time series market timing factor model for one -#' or more 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 compute excess returns. -#' -#' Estimation method "OLS" corresponds to ordinary least squares using -#' \code{\link[stats]{lm}}, "DLS" is discounted least squares (weighted least -#' squares with exponentially declining weights that sum to unity), and, -#' "Robust" is robust regression (using \code{\link[robust]{lmRob}}). -#' -#' If \code{variable.selection="none"}, uses all the factors and performs no -#' variable selection. Whereas, "stepwise" performs traditional stepwise -#' LS or Robust regression (using \code{\link[stats]{step}} or -#' \code{\link[robust]{step.lmRob}}), that starts from the initial set of -#' factors and adds/subtracts factors only if the regression fit, as measured -#' by the Bayesian Information Criterion (BIC) or Akaike Information Criterion -#' (AIC), improves. And, "subsets" enables subsets selection using -#' \code{\link[leaps]{regsubsets}}; chooses the best performing subset of any -#' given size or within a range of subset sizes. Different methods such as -#' exhaustive search (default), forward or backward stepwise, or sequential -#' replacement can be employed.See \code{\link{fitTsfm.control}} for more -#' details on the control arguments. -#' -#' \code{variable.selection="lars"} corresponds to least angle regression -#' using \code{\link[lars]{lars}} with variants "lasso" (default), "lar", -#' "stepwise" or "forward.stagewise". Note: If \code{variable.selection="lars"}, -#' \code{fit.method} will be ignored. -#' -#' Market timing accounts for -#' the price movement of the general stock market relative to fixed income -#' securities. It includes -#' $down.market = max(0, R_f-R_m)$ as a factor, following Henriksson & Merton -#' (1981). The coefficient of this down-market factor can be interpreted as the -#' number of "free" put options on the market provided by the manager's -#' market-timings kills. -#' -#' \subsection{Data Processing}{ -#' -#' Note about NAs: Before model fitting, incomplete cases are removed for -#' every asset (return data combined with respective factors' return data) -#' using \code{\link[stats]{na.omit}}. Otherwise, all observations in -#' \code{data} are included. -#' -#' Note about \code{asset.names} and \code{factor.names}: Spaces in column -#' names of \code{data} will be converted to periods as \code{fitTsfm} works -#' with \code{xts} objects internally and colnames won't be left as they are. -#' } -#' -#' @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 mkt.name name of the column for market excess returns (Rm-Rf); this -#' is necessary to add market timing factors. Default is NULL. -#' @param rf.name name of the column of risk free rate variable to calculate -#' excess returns for all assets (in \code{asset.names}) and factors (in -#' \code{factor.names}). Default is NULL, and no action is taken. -#' @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{mkt.name} and \code{rf.name}. -#' @param fit.method the estimation method, one of "OLS", "DLS" or "Robust". -#' See details. Default is "OLS". -#' @param variable.selection the variable selection method, one of "none", -#' "stepwise","subsets","lars". See details. Default is "none". -#' \code{mkt.name} is required if any of these options are to be implemented. -#' @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}} -#' -#' @return fitTsfm returns an object of class \code{"tsfm"} for which -#' \code{print}, \code{plot}, \code{predict} and \code{summary} methods exist. -#' -#' The generic accessor functions \code{coef}, \code{fitted} and -#' \code{residuals} extract various useful features of the fit object. -#' Additionally, \code{fmCov} computes the covariance matrix for asset returns -#' based on the fitted factor model -#' -#' 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}{length-N vector of estimated alphas.} -#' \item{beta}{N x K matrix 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 -#' \code{variable.selection="lars"}} -#' \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 Yi-An Chen. -#' -#' @references -#' Christopherson, J. A., Carino, D. R., & Ferson, W. E. (2009). Portfolio -#' performance measurement and benchmarking. McGraw Hill Professional. -#' -#' Efron, B., Hastie, T., Johnstone, I., & Tibshirani, R. (2004). Least angle -#' regression. The Annals of statistics, 32(2), 407-499. -#' -#' Hastie, T., Tibshirani, R., Friedman, J., Hastie, T., Friedman, J., & -#' Tibshirani, R. (2009). The elements of statistical learning (Vol. 2, No. 1). -#' New York: Springer. -#' -#' Henriksson, R. D., & Merton, R. C. (1981). On market timing and investment -#' performance. II. Statistical procedures for evaluating forecasting skills. -#' Journal of business, 513-533. -#' -#' Treynor, J., & Mazuy, K. (1966). Can mutual funds outguess the market. -#' Harvard business review, 44(4), 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[stats]{fitted}}, \code{\link[stats]{residuals}}, -#' \code{\link{fmCov}}, \code{\link{fmSdDecomp}}, \code{\link{fmVaRDecomp}} -#' and \code{\link{fmEsDecomp}}. -#' -#' \code{\link{paFm}} for Performance Attribution. -#' -#' @examples -#' # load data from the database -#' data(managers) -#' -#' # example: Market-timing factors with robust fit -#' fit <- fitTsfmTiming(asset.names=colnames(managers[,(1:6)]), factor.names=NULL, -#' mkt.name="SP500.TR",rf.name="US.3m.TR",data=managers) -#' summary(fit) -#' fitted(fit) -#' -#' @importFrom PerformanceAnalytics checkData -#' @importFrom robust lmRob step.lmRob -#' @importFrom leaps regsubsets -#' @importFrom lars lars cv.lars -#' -#' @export - -fitTsfmTiming <- function(asset.names, factor.names=NULL, mkt.name=NULL, rf.name=NULL, - data=data, fit.method=c("OLS","DLS","Robust"), - variable.selection=c("none","stepwise","subsets","lars"), control=fitTsfm.control(...),...) { - if (is.null(mkt.name)){ - stop("Missing argument: mkt.name has to be specified for market timing model.") - } - - factor.names <- union(factor.names,mkt.name) - - fit.Timing <- fitTsfm(asset.names=asset.names,factor.names=factor.names,mkt.name=mkt.name,rf.name=rf.name, - data=data,fit.method=fit.method,variable.selection=variable.selection,control=control,mkt.timing="HM") - -return(fit.Timing) -} From noreply at r-forge.r-project.org Sun Feb 8 01:25:24 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 8 Feb 2015 01:25:24 +0100 (CET) Subject: [Returnanalytics-commits] r3597 - in pkg/PortfolioAnalytics: R vignettes Message-ID: <20150208002524.EC8B9187A26@r-forge.r-project.org> Author: rossbennett34 Date: 2015-02-08 01:25:24 +0100 (Sun, 08 Feb 2015) New Revision: 3597 Removed: pkg/PortfolioAnalytics/vignettes/ROI_vignette.pdf pkg/PortfolioAnalytics/vignettes/custom_moments_objectives.pdf pkg/PortfolioAnalytics/vignettes/risk_budget_optimization.pdf Modified: pkg/PortfolioAnalytics/R/constrained_objective.R pkg/PortfolioAnalytics/R/optimize.portfolio.R Log: Use .storage environment instead of .GlobalEnv to store DEoptim objective results Modified: pkg/PortfolioAnalytics/R/constrained_objective.R =================================================================== --- pkg/PortfolioAnalytics/R/constrained_objective.R 2015-02-04 00:29:05 UTC (rev 3596) +++ pkg/PortfolioAnalytics/R/constrained_objective.R 2015-02-08 00:25:24 UTC (rev 3597) @@ -45,7 +45,7 @@ out=0 # do the get here - store_output <- try(get('.objectivestorage',pos='.GlobalEnv'),silent=TRUE) + store_output <- try(get('.objectivestorage',envir=.storage),silent=TRUE) if(inherits(store_output,"try-error")) storage=FALSE else storage=TRUE if(isTRUE(normalize)){ @@ -283,7 +283,7 @@ #add the new objective results store_output[[length(store_output)+1]]<-list(out=as.numeric(out),weights=w,objective_measures=tmp_return) # do the assign here - assign('.objectivestorage', store_output, pos='.GlobalEnv') + assign('.objectivestorage', store_output, envir=.storage) } if(!isTRUE(trace)){ return(out) @@ -379,8 +379,13 @@ out <- 0 # do the get here - store_output <- try(get('.objectivestorage',pos='.GlobalEnv'), silent=TRUE) - if(inherits(store_output,"try-error")) storage <- FALSE else storage <- TRUE + store_output <- try(get('.objectivestorage',envir=.storage), silent=TRUE) + if(inherits(store_output,"try-error")) { + storage <- FALSE + warning("could not get .objectivestorage") + } else { + storage <- TRUE + } # use fn_map to normalize the weights if(isTRUE(normalize)){ @@ -763,7 +768,7 @@ #add the new objective results store_output[[length(store_output)+1]] <- list(out=as.numeric(out), weights=w, init_weights=init_weights, objective_measures=tmp_return) # do the assign here - assign('.objectivestorage', store_output, pos='.GlobalEnv') + assign('.objectivestorage', store_output, envir=.storage) } if(!isTRUE(trace)){ return(out) Modified: pkg/PortfolioAnalytics/R/optimize.portfolio.R =================================================================== --- pkg/PortfolioAnalytics/R/optimize.portfolio.R 2015-02-04 00:29:05 UTC (rev 3596) +++ pkg/PortfolioAnalytics/R/optimize.portfolio.R 2015-02-08 00:25:24 UTC (rev 3597) @@ -158,7 +158,7 @@ if(isTRUE(trace)) { #we can't pass trace=TRUE into constrained objective with DEoptim, because it expects a single numeric return tmptrace=trace - assign('.objectivestorage', list(), pos='.GlobalEnv') + assign('.objectivestorage', list(), as.environment(.storage)) trace=FALSE } @@ -201,8 +201,8 @@ out = list(weights=weights, objective_measures=constrained_objective_v1(w=weights,R=R,constraints,trace=TRUE)$objective_measures,out=minw$optim$bestval, call=call) if (isTRUE(trace)){ out$DEoutput=minw - out$DEoptim_objective_results<-try(get('.objectivestorage',pos='.GlobalEnv'),silent=TRUE) - rm('.objectivestorage',pos='.GlobalEnv') + out$DEoptim_objective_results<-try(get('.objectivestorage',envir=.storage),silent=TRUE) + rm('.objectivestorage',envir=.storage) } } ## end case for DEoptim @@ -465,6 +465,11 @@ return(out) } +.onLoad <- function(lib, pkg) { + if(!exists('.storage')) + .storage <<- new.env() +} + ##### version 2 of optimize.portfolio ##### #' @rdname optimize.portfolio #' @export @@ -731,7 +736,7 @@ if(isTRUE(trace)) { #we can't pass trace=TRUE into constrained objective with DEoptim, because it expects a single numeric return tmptrace <- trace - assign('.objectivestorage', list(), pos='.GlobalEnv') + assign('.objectivestorage', list(), envir=as.environment(.storage)) trace=FALSE } @@ -801,8 +806,10 @@ out <- list(weights=weights, objective_measures=obj_vals, opt_values=obj_vals, out=minw$optim$bestval, call=call) if (isTRUE(trace)){ out$DEoutput <- minw - out$DEoptim_objective_results <- try(get('.objectivestorage',pos='.GlobalEnv'),silent=TRUE) - rm('.objectivestorage',pos='.GlobalEnv') + out$DEoptim_objective_results <- try(get('.objectivestorage',envir=.storage),silent=TRUE) + rm('.objectivestorage',envir=.storage) + #out$DEoptim_objective_results <- try(get('.objectivestorage',pos='.GlobalEnv'),silent=TRUE) + #rm('.objectivestorage',pos='.GlobalEnv') } } ## end case for DEoptim Deleted: pkg/PortfolioAnalytics/vignettes/ROI_vignette.pdf =================================================================== (Binary files differ) Deleted: pkg/PortfolioAnalytics/vignettes/custom_moments_objectives.pdf =================================================================== (Binary files differ) Deleted: pkg/PortfolioAnalytics/vignettes/risk_budget_optimization.pdf =================================================================== --- pkg/PortfolioAnalytics/vignettes/risk_budget_optimization.pdf 2015-02-04 00:29:05 UTC (rev 3596) +++ pkg/PortfolioAnalytics/vignettes/risk_budget_optimization.pdf 2015-02-08 00:25:24 UTC (rev 3597) @@ -1,3309 +0,0 @@ -%PDF-1.5 -%???? -3 0 obj << -/Length 1348 -/Filter /FlateDecode ->> -stream -x??XKs?4??W?B?? - ?????[,E?VH-?????????S????????{fB 'I-???????m?.????????Y?3&x???M??b??A?s???f??U??Xk?^E*N??+??mg7m]??H?"|s??????U??Sew4?z??tX\??vXo??W?????K?,??`y??c?g?x?????lU?{ rw?N?"G2gZ????`????)??$????Hg???Z)?5?H?(?y,D?? -??j?[??,0+?@???+??*?e???Y?????/h? ?g?$???4?.???E?S3??L -z0?(???e - -?c????G???wM??J??}?????^?OAL?y; -???Gs"?TSC}??#??EGv???e:'>??96?????v??3~?C??b?????kk??-?Mf-?!*5?@?M??????E?D?&?? -*??fg?hm?v?????j??v-?~??wV??ZUM??5-?E??+"* ?o?Zx?.&P??,?1?vJ5g{0) 3I^??O???i\2gc??????y???&????J'??<8F??{F{>?? -;#???)???i??L??qB?*Cn???? ?.? <E?X? -jLW??)???vy?3??{"?c??????Q??M!?2;????6??'???C?K?8y???z3?F~??xm3?? w???a?z?rL?????#N ???tC?O,U???S???8???Y?gca??????Og?r? -endstream -endobj -14 0 obj << -/Length 2667 -/Filter /FlateDecode ->> -stream -x??k????{~??OZ4b??(1m -?]6? -p?.????????,??????w?C?lnvs=?_D?F??_NV?U????????}??=?+??zu?]???L???3???v??g????*V??e]?/?v=???H???*Y??]?????#???????9I?# ?Q?u?]?@??????m?'???e???:??_7u??EY??}?o?=???????_?.c?1#%??i ????q?y????h+??o?gQ?W? O?2? ??-}??Wz????SK? ?E@?;?R???r??????????t?o?E[?{?"??*?(?-={?A?$:?c?????%?D;b??_5???`??\wx?????Y?P???=???OM?o??lwam)X[.????]?2:???B{?/}????J4?{??i?$b?$?k?????A?E ??BE??#??????/n?=x??hU9? -(??????N?????B?4I??{?R9??(?????????d?(??????z?GU,???? ?Y?????n[o??n?????>?R?1??????FC?[??????????w?n????`??Ht????dR?? /????H?1??f&??!?Z??9?}?Xj????j5??nMO??&Zd?$?r8(Y^5?d5????9 KA??@??oI? ?r??0LB????RF??0?0?0?8??(???C? ? -?j;??L]??O????aY??%??$?@??G}8K??3?s??????TL???????+??5???b$????R?Yl?sY?.X??????B???E?*?Q??"?~?x\z?` ?R??/O;H ?{KeT?)^XS?* ?#U??x??s ?SM??%?a????????!?2?????%??OPtF???b?????.?X&r?R?X??"M@??? -??????i ????3??? Da??????p&U?9??tt?4?r.Q? F!?e?8t(>_?\????&?<+??????g? ???'??}8?Q??#???[?S -~ ?"?s?qo?D??-?? -I????YB??B? ??+??HXFj?? t?S????t?3?\???S -E????_??*f? - ???i-4ktu??wg!??"???zc??A?????????\ ?D?C?[?????w?g???!??3?C&}&X -?g&?.??n????r??0 ? ???$?%? ??$=?Cg??i_?C?A?D????-K2 ?Ul?i??h??t?/?D? -???3??;????>?????=??x?g??l???oF??G?? ?????'7?U??????TUdmn ?? -?<4nr?x????2$)YzA?XP ?? -= ?W???;?{??-=??^=}?????p?????????f9q?]?%??a~?F8&M??????L?????b?F?4m[?hs?M? ???9??.;??O????IE8i/{?GZ>`@??CQ 5?L?!S????\^???.(????}???~}?G?M ?{(??SEw???J???n???3?c[?????????y???yE ???n????'_k}??? ~f???Qnb?=? -((??o?i?Ph??YH"X?? XcJT??]? ???C?sk??[[??`??A-?8??`!T?$P+M3????e????K??? -?1???<`U?.??(????Gu??Nl.hrX??????NC? -???y@x???????d -???f??"z?!????w??JEe=?!?6P?U??r???? ???????N?n???c????0d? >S???d?+???4j2?qHB?8?? -?U ?w=mF?g?ry9????*?????k????$?5_l6l??w? -????8???_C31 -???y?p1????{??P???_i?X??NELs??iI?%:?%<(hfwa????}a -?i??o2?????(?L????0??????w??QL7|??IG0??ic????Y?_??g|?KF?????R???>?Xr|s7?+?L??G%??????-??@9+?????8? ??2m?d??????????@??4 ????-?@ -endstream -endobj -25 0 obj << -/Length 1686 -/Filter /FlateDecode ->> -stream -x??X???F????Hd?z??UK??E?z?~???O{Oa*???????A???B?&?? O??:?????|{ ?}gJ?Q?q??{G?`???ngZr????a??(T???8 -&???3????2??????b??Lp???^???c9?\??lKb?,??Y??0Iz????J/Q?C????i ???Qtc???7?N?[??K??8?????d?$?^eEV?g??=?~SW}O?(??7{???????Jcz?(?T?RjQ#??I?G???? ???!"]b?bvB|???w??mq??`n?d?&AM???vm??????n??????l??p#r???zS?Z?X??????d_!-m?!Q5?Ar??[??U ?6+??????? m?w --7M]????????o&??^? -???:?*'????e/?tn??D??8`??x -????8l?Z??1&I|N??DgC!?y??e??????,?6?&????A?;???I??????D7?u.D??)iL?G>??>??Dy0b at O?f?[???h?Y?;:?a4?Q5qq?i??vz?h?????[????@?T????\ ????HDR???@????Fm??lZ_??'T?^$>?^??E?aaF???}f?6???_I*?dhM/{`za9uf=?=@J$?al|??;H ??????M9?4??q?"SUw,?? +5c????g]h:??m -??Z??\KK?_=???P???1fM?????]?T#??m?A?????B?>?h????&??f????xf???b/??(?????7?? '? vY?????????]n?5F"????4+??#????s -S??r??5" F?p???\?A3?D/?Y?e??p???k?y}?j*??=???>??;???mWH?Y??7?? -??{UV!?Of???-??:y%?C???l???????? -L"%N???5c???J??.??1'????????;????G???g?S -|0I???N???,U??q??S! -endstream -endobj -30 0 obj << -/Length 1477 -/Filter /FlateDecode ->> -stream -x??XKs?6??Wp?C??!?:???$???D?O?!??TD????? E?vR[V:?E??>>,w?L??a}1^?????8?????: ??# -? -4'T?@HA$??ly?t?)??x???2X?`~???U?B?z0??????rz???????L?y????Dh"8 ?Yp>{69?? F4!f@???????????>Tv?<,9??xw?? `??Lsge?6?#L{?Z??P???V??X?y??k[??z???7??]l???"??'P? ????B???#?m?v????????uS????:>?^??H9??O? -?En????nIg??y??-l??^m???1???^?Y>?g?H??y??N??)>"???t??S$$N??KoAc??;??19?B;???????d?d}vo??*?ti??U?\????j5??t;??&????\:??g???W?n?'??~:L?c*?2?U?p???{???k??fe;?Q?"????c?3eT~1I$3?+??}??5?$?????\0????????S;?=?>yB?&?????k?????:?K[7P?4?@????(?v?k/? -??]?Xn??}???> S??d???e??c???m0?????W?,?m[?!?y??%r???????? u?2??H???sc?:???M?r?\)?E?c?A ?6#?H??S?a??j??3?F1]/?YZ?Y?f?XVn?????2?LKl*t?????B?/o=??tS4?????h'?TVV?eZ?Q'?w^9?Q??????? ??p?,mZ???'??&?w????v2????&m?I I}8???n?^????;??>???+r?gy????|??E ??????9k??ju???????????????|U???Q{?g?. -?~??W?????@????? -endstream -endobj -34 0 obj << -/Length 1452 -/Filter /FlateDecode ->> -stream -x??Y?o?6?_!? 1?o??????a?:???"?m:QjK?$'???E???k??.??R???????I88 p?k???Qo?5??BJR?fA,?X ?8??h??WIy??0?m??P -VJ?? -?TL?j? |e?????)?_???@v[[??????>?????Q????g?M????l??pDs?2???.??????1?????I8)??>?B?4?*b?7?L??????&??E&R?9??l'?)????,-?\??? -d?{ ?? h -?Y??7???6???G???]q@??!?@p -n?E??9#?< ?L? f??????,~L??E?Q0?_I??%}?H?!N0C??????i6?0?????q:??Y\{????@PQQ -??o5?c ?)?i-=7??X ?HSa????M -N?=7 k?!I???)??2??Y6O????7??l?_?q8?W???yR?> -???S?4????? -1?,?n?1????y3T?8?:?[T?H?c|q?4????"?????N?V} N???????????????9q?????&?*v??????-T??{?^????wz??yU0)}@? ???ja??x?????;??(m???H??mP7?s3= -?j??' C9??6?9?d????c6scY?g7i8?\? ?ye_???y?? 8??M????HP at 0?\???'z?????~??????48?U???>~?? -P &?:?%?%?4?G?????JV?J?d?[k?|Z????z??_`? r-M{??l?\U?>????)???[????????JP$?u???j?>~H$?{??&???9??W??]????p4?????>~|?g?r??C??=\N=n~[h7?????????iK?<?4?5A??????FM?\?????????????? ?j???a?*??F@?A?x???U"????|? -G0GGOU????/?pbwG?'O?> -stream -x??Ymo?6??_!?"6????C?% ?Ro??#??Yr%:I??w?X????K????O?;??s??X??w?j????O{8??w{ I!?sgh???w???G?"? a?$QS?H,?t?g?#F?1 -E?DA?????;[????'?z?????@?iT?i?p?q?(??x? -_??"?q?vH?g???F$F????<|K?gn???Y??=??/O??8A"$?(1?(????U??$ -U5[-t1?Ihj??n4s?&?U?Hh???>l?a ???f??7Nf???ER?5?F??kY? -U?z??+?r5????H?1mw?????!~??%?`$?Y3?CS:]('?*????1??????-?*56dXNad8???? ]????? ??%??ee?e??n?i???z ????????? ?m??5??UV?e?????`2QF9?U??????k?l N?0??*??]\????#??O??????!????$9?1?fAI0?8????2??|?b??9??K???\??zr????N4?O?H?M+????V?yJ??&??w????3KT??;Wn????Y?_?a??4n??????Pe?-6':?|???We?m?n??v?@c?b,>??^?8????um??2zC;?????C?`?Y??????D;*{V?u????D?j58?Z???p?BU?5_cp( -=?h/????e??????{n?IJl????c?5??(~Q$L??o]? ?[?? :J?3W|???\????3D??!v????????CJ??1?3?|B? ????~??e??}?~? -?2F???f??F?j?#???[???\>?Gw??w?.n'?]^^??p???PU^h?? ?7????\??Ak?o?????~???????? ???K ????2e???????u???v 6!??~Q????89P??=?X -endstream -endobj -40 0 obj << -/Length 985 -/Filter /FlateDecode ->> -stream -x??Wmo?6??_!??????????I?a?0??>?E K????\IN????D???%???E??????????????q?????????????[??< ?;??">w??H'L??3????%??\;????1.??????????l0???Q?:??l?? 0??>??:???t??~??G?C?-?jG? -??,??:N?f???`?O?#?v??8?S???8z??#?g?? ?j??m7???tX?q\?????y?%ft???'??N????? -??Q??fA??????8o?uB??l:}??/^E?????B??4?????W?????P;??S??A??'??c?????O??{????R???)???????E *??wq'CF? -d?????*?3 ?4?i?^?Ag?Qgs???*$??V??/6iX[?9?Dv"??? 8R????cnY? c?Mj4?R??%^?????3 ???W?????U???Z?0c?w -???M????????~?a?!??n??????=???u?j?@?????+e??????Z??????y???V=?4?t?? -?t???;?9??D2 ??=??^5(?8??mi??=I;?\2?6?s?~?I?"&2???????f?jFq??ta?I$I?A??????4?<u?FWC?R;|"_??W??lS>??R?_?G}=???????;/???1???S|a??X???>d?!{??G????&??? -endstream -endobj -44 0 obj << -/Length 988 -/Filter /FlateDecode ->> -stream -x??V?o?6~?_A?&6??Y?/ -?a????? P$:?&K?D7???(???t??k_$??x???<~s!"?_u7?????` -???UX????_c??>??~BA)??HR?9U(YO?^p?i$?????????!??7?????H?r???0p ?gh?????????'@8??=?\2??????f??????2????????????5'???}n??`???^ ??]?q)g?o?`K??V???fe??F2??????,?z:g??'???6?d??~,??tz?^??R?i???{?AU%f???????g?z]?^?????X2??7N%q?"Dj?w2#phxO!eO?,??&x???6?79_e?f?c??|????D??Q??Us??k????? -? X ? ??%???6U<0?? ? ??0eQ`?l9???S???b?'?*????U`????OH?cgh?]Ww?NX/??sA????p?`??6?r9??? -????2?J??[??K??~?f?????/?F?????p??d_?Q?????(????????????M?,? ?]?@ ?{O !?n?{"IV??OS???J\?Lv??mwy?????m?r???m??l>~?C=?OO?L???6?? ?Y?????S???p?+f?????m?M??#???Y??? -[??????U? -+)???0???\^?j???U??+-G/?????w?3f}???_??????????????q??C??????0,?s -7$????$`????i9(??????????}b <3?a?#r??6?@t?FY?iZs????C??2?;w+7?~r?_f??`f??9d????^m?*???H???U?q??????j?6?????$??.?????????I??????!bn?? -"V?f ???]??C??S???fM?-??aj?7?l?R4?????([???Fc????_?c???????7?(???J?uT`d\?[ -endstream -endobj -47 0 obj << -/Length 2136 -/Filter /FlateDecode ->> -stream -x??YYo??~?? l???V_??{?2?N?(??f!Pd? ?r?????OUW?Cr{ul????fuU?W???????w?oo/??E?%, e??n?8d"R^???ns???j?Z?P??.-q?|???H??M?D:??2????T??"Z]4???????Ov?mZo??)W?U?z???? ?$??X??$N?????^s?h?D?0bI???j(?????+?9???j??7M???'??52??JrF???T)b??u??E??P??6?????A?}????????6???w?hC?MWZN??? ?G?7y?[o?|?'?>z????G?~{{???rOx?b"?^(b???H?JT??LK?6???o???q?~???&???k???????O?? %????HE?'P?7 ??9??????`Zq??4?sV?????u??k@????hEZ?K ]F?=??/?P?Q?iN7??W???NJ? r53OF-]vQ?*oh?d???!?t??5??]?P???&m??????k/ ?G?nMij???Ch;W_?????? 7??????????4??4M/???g"ZK???H2?d??4?Zj??I`1???J~??U -?Z???@??lIm=???Q??[W?n???(?? -?f`?"??q?}????%?4?kIeN???M68??m ??U ?uU7d??\???g???????o?/"M?r?? ???m?ab(A? !?jH???`.????i???KE??uqQi?cD?V???)N?%?Otu.Yp???d?? -?S@Sb~??N at 9l#/???\??:@??mv???YHQ???`?:x%:|???????qo-B?.l -GKG?V&p:??6?????N?3@??kL?6???48?Un????Z?3?]cF???n!?b?????gG??8?Crf??r?Q??l??Zz???y??????3? -?M??z???#( -?@?Gi?}a??+??GO[A???\t???q??z?0???,??]ie??q kIG?H???8???i?-q??????' ????u?(X????? (Gu???? &%(v >??^Kh???>nS{??oR???wh9?t?IW|??q*??O???J??T?5kJ?ldO???_?????$??l??0? -*t??l???P???w>???>{,?q??n03'??P????!w???ol1?F?;?84i?&+6E?"$?\??#??'S????JF,8??A'??<_?H1)'?| -???'????????=?????;????9??K?J???0??}*?f8[Kh????3???sZ?Wi1?????D??I???1?? -zW?'O?????? -endstream -endobj -50 0 obj << -/Length 1438 -/Filter /FlateDecode ->> -stream -x??ko?6?{~??`?3?,?z??tM?u?e???+Y?m?????&??;?'Yr?l??vj?x??-???"n?4v????????$?;?^O?![??????????? ?v=?c?{???1?H ??}ly??1{????NS??dW???N???????U??%?D??>?d??????^"bnGFv?,E??????r??\??=@??Ka:????o -? D?`?? -???eB??7???Q?\??K?p?2? ????????gq??b; ???????F????!=?!_?.n??0)?~?|~, ?????/??????yd |?J?|{???H?u?{????R???B??????f?u??:H??e?|U5}????? $a???w>I?X_?3???f???].u???m??????nEJ??"Z\? ??SJ?9???????-? ??????:E;?g???{?t????z||W?t??=j??????h??'??.??JB|?:?????[???"????????=??????????????$?#??:Mu??g|???e'A???K\~?I?xP?=??v???? -?t??S;Wv???? -??B0%??????^6??Q -??g?wS?]p?nJ9?6???fS,F??\?z??????j? -?N ??}#??In???tx?M???F??4"?.z??? ?X?V-5> -stream -x??X?o?6?_!?&1?oI???:????C?L?*??Jr??????dI??8E??y?x??x??}????qp?S???s?? v`???q?P(CM?>?{w?h?O'4?q?H?N)??;qv??9#???a?#????Y??q?J???j~rv.B'??T:??H??9>g??/?+????TP?????????7PvJ|???:????+?zU?I???.???$_???:?T?8????????O?R????r?????e?t???E%?U**???)??c??R?Q<\?_???????YKjUf??????(j ??D?%?T????"??/?????U?/+??`???>m?:Q??????tv.y??I r?o??lY.!e?z:?l|]dY??3Z?) ???}???P??J?8?=????G??}s??TTmJuGk????kBAz?6q??er???"?3????B8?$?`=2D???]?]\/8?f?? ???30dK?:????iQ|?????s"??pr?? -?cn-x??O?8'->&?????rD -???L?=?THL[??r?Gj????9?????:?\?Z???w???We??Q?Vv?KTEz????JK'U???t?T???]???-??)g??5?A^??3nS??????????=??@0 -??TQ -*?Sn??_?$pp??\??O???i??LM??O?????4???u???H(?!2?T"O?A?4??(?> -stream -x??W?o?0~???T????>???=???&?a-?KW?B?i!-???.qH -4 at l?4??s?|????0*?"????~Y????-F??q?U?j[??PY?O?l??D??XP?%a?Q? ?V9/P0?h?T C?)?>? i?p?g}?o?]*K,B????$?? F*cN?#r?99?F??N????m?#???V???7p?F???l_|m????f?n??Fh?:_???y1?????????&x??^????R4 -??n^?z?[Q?U?7:??????h????L??0?????yv?d??2s???O??K?!?Byez?*/gWx)?C?`!> -stream -x???MOA ???#qhP??=??? -???z(??Tj!T? -????3? ???rYvg??g??;Xb1???_???r?~F??^?E??Sy??Too????5#0h"Y?l?? -?????|????z -?~n?&?G?4f??????$?4?y3?2?kdG?????|?????dj???????R?,x?/ L?"???/E?????>???+0????S??-'???? ??,?|? -??H@????S?~?Ve????/???bu???????rV?pys????: -ee\*????,1?*c??A??Qj,0-??#GYs??+0?#@??$L??u?a??T?f??g???!=?V?9*???V?1???????l????Sy??dJ?r8TZWW -A?-? ???N???8Dam?Y? ??9&???]???\NY?_?2]>???<>e?????I??z<4???????[?Pm????7p???8+p> -stream -x??T?n?0??+?"?}?I????Em?,YFm3?d????H???v?=??Y???|?????i?~4??&A -?? ???????4|q?sB?A??Hi????X'>.8?T d$6???DU?p1?Kv{=K?w?" p???BF??0Xp?fs?=???d?????'?tf?LqBR??U?Lh??`?s? v?Q???p??3??N??5??? ???P????'o??_W#8??_??=??jteT`+??z? ??;`?lZ???x?dL?ep?????qk?2iW?d1???? -~W??Y??j?]???K?^??n}????"m???Y?1SG P?? ??.?\, ??m??????e??m?/??vv:^?XKv<^8???1^??Zs?]???U??88 9?N???N??V????? -?z4B?F??C?D????\?G?????-???o?Q?c?k? -Z[9?????????;H?)???91^?? ???P???>1?b`z??????v?r(?????u/??a?,?? -???(?x????????? -endstream -endobj -61 0 obj << -/Type /XObject -/Subtype /Form -/FormType 1 -/PTEX.FileName (./figure/unnamed-chunk-181.pdf) -/PTEX.PageNumber 1 -/PTEX.InfoDict 66 0 R -/BBox [0 0 432 288] -/Resources << -/ProcSet [ /PDF /Text ] -/Font << >> -/ExtGState << ->>/ColorSpace << -/sRGB 67 0 R ->>>> -/Length 20 -/Filter /FlateDecode ->> -stream -x?3T?R0T?R(? -??m -endstream -endobj -68 0 obj -<< -/Alternate /DeviceRGB -/N 3 -/Length 2596 -/Filter /FlateDecode ->> -stream -x???wTS????7?P????khRH -?H?.*1 J??"6DTpDQ??2(???C??"??Q??D?qp?Id???y?????~k????g?}??????LX ? ?X??????g` ?l?p??B?F?|??l???? ??*????????Y"1P??????\?8=W?%?O???4M?0J?"Y?2V?s?,[|??e9?2?<?s??e???'??9???`???2?&c?tI?@?o??|N6(??.?sSdl-c?(2?-?y?H?_??/X??????Z.$??&\S???????M????07?#?1??Y?rf??Yym?";?8980m-m?(?]????v?^??D???W~? -??e????mi]?P????`/???u}q?|^R??,g+???\K?k)/????C_|?R????ax??8?t1C^7nfz?D????p? ?????u?$??/?ED??L L??[???B?@???????????????X?!@~(* {d+??} ?G???????????}W?L??$?cGD2?Q????Z4 E@?@??????A(?q`1???D ??????`'?u?4?6pt?c?48.??`?R0??)? -?@???R?t C???X??CP?%CBH@??R?????f?[?(t? -C??Qh?z#0 ??Z?l?`O8?????28.????p|??O???X -????:??0?FB?x$ !???i@?????H???[EE1PL? ??????V?6??QP??>?U?(j -?MFk?????t,:??.FW???????8???c?1?L&?????9???a??X?:??? -?r?bl1? -{{{;?}?#?tp?8_\?8??"?Ey?.,?X?????%?%G??1?-??9????????K??l?.??oo???/?O$?&?'=JvM??x??????{????=Vs\?x? ????N???>?u?????c?Kz???=s?/?o?l????|??????y???? ??^d]???p?s?~???:;???/;]??7|?????W????p???????Q?o?H?!?????V????sn??Ys}?????????~4??]? =>?=:?`??;c??'?e??~??!?a???D?#?G?&}'/?^?x?I??????+?\????w?x?20;5?\?????_??????e?t???W?f^??Qs?-?m???w3????+??~???????O?~???? -endstream -endobj -73 0 obj << -/Length 385 -/Filter /FlateDecode ->> -stream -x??TMo?0 ??WX?@ZCR???mL?mSo?4?R>4?]W4???-E?? T?n???8g(?M1;7??>?@S@??*Ak8\0! Hc?u?U?0g%???zb??q?V?f?=????iW?=SG??[G????0????(+???D?n$ 2N*?????????f?AS -V_????N??????W?a?G:G -# -???]B??y?Y?'????Y???O?-~l???R?C??m?X????W4??Ut?8l at wu????GQ?????p3?????-2m?O=??7?PE?[PV?????#\D@?I??m?C?J'O??$[??b?9?"A4 ?l?6?x?I/K?'???^??Kw??%&?0????_b??A?"?w"??8?A]???8u?F???A?9? -endstream -endobj -62 0 obj << -/Type /XObject -/Subtype /Form -/FormType 1 -/PTEX.FileName (./figure/unnamed-chunk-182.pdf) -/PTEX.PageNumber 1 -/PTEX.InfoDict 74 0 R -/BBox [0 0 432 288] -/Resources << -/ProcSet [ /PDF /Text ] -/Font << /F2 75 0 R/F3 76 0 R>> -/ExtGState << ->>/ColorSpace << -/sRGB 77 0 R ->>>> -/Length 989 -/Filter /FlateDecode ->> -stream -x??V?n\7 ???????????6?"Z??YY????? -w??K?z??M&L?91J???O???L?<{??????????jf~???*i??5???????yr-??/?? -endstream -endobj -79 0 obj -<< -/Alternate /DeviceRGB -/N 3 -/Length 2596 -/Filter /FlateDecode ->> -stream -x???wTS????7?P????khRH -?H?.*1 J??"6DTpDQ??2(???C??"??Q??D?qp?Id???y?????~k????g?}??????LX ? ?X??????g` ?l?p??B?F?|??l???? ??*????????Y"1P??????\?8=W?%?O???4M?0J?"Y?2V?s?,[|??e9?2?<?s??e???'??9???`???2?&c?tI?@?o??|N6(??.?sSdl-c?(2?-?y?H?_??/X??????Z.$??&\S???????M????07?#?1??Y?rf??Yym?";?8980m-m?(?]????v?^??D???W~? -??e????mi]?P????`/???u}q?|^R??,g+???\K?k)/????C_|?R????ax??8?t1C^7nfz?D????p? ?????u?$??/?ED??L L??[???B?@???????????????X?!@~(* {d+??} ?G???????????}W?L??$?cGD2?Q????Z4 E@?@??????A(?q`1???D ??????`'?u?4?6pt?c?48.??`?R0??)? -?@???R?t C???X??CP?%CBH@??R?????f?[?(t? -C??Qh?z#0 ??Z?l?`O8?????28.????p|??O???X -????:??0?FB?x$ !???i@?????H???[EE1PL? ??????V?6??QP??>?U?(j -?MFk?????t,:??.FW???????8???c?1?L&?????9???a??X?:??? -?r?bl1? -{{{;?}?#?tp?8_\?8??"?Ey?.,?X?????%?%G??1?-??9????????K??l?.??oo???/?O$?&?'=JvM??x??????{????=Vs\?x? ????N???>?u?????c?Kz???=s?/?o?l????|??????y???? ??^d]???p?s?~???:;???/;]??7|?????W????p???????Q?o?H?!?????V????sn??Ys}?????????~4??]? =>?=:?`??;c??'?e??~??!?a???D?#?G?&}'/?^?x?I??????+?\????w?x?20;5?\?????_??????e?t???W?f^??Qs?-?m???w3????+??~???????O?~???? -endstream -endobj -69 0 obj << [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3597 From noreply at r-forge.r-project.org Sun Feb 8 01:57:59 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 8 Feb 2015 01:57:59 +0100 (CET) Subject: [Returnanalytics-commits] r3598 - in pkg/PortfolioAnalytics: . R demo man Message-ID: <20150208005759.DF60F18788F@r-forge.r-project.org> Author: rossbennett34 Date: 2015-02-08 01:57:59 +0100 (Sun, 08 Feb 2015) New Revision: 3598 Added: pkg/PortfolioAnalytics/man/chart.EF.Weights.Rd Removed: pkg/PortfolioAnalytics/man/chart.Weights.EF.Rd Modified: pkg/PortfolioAnalytics/DESCRIPTION pkg/PortfolioAnalytics/NAMESPACE pkg/PortfolioAnalytics/R/charts.efficient.frontier.R pkg/PortfolioAnalytics/demo/demo_efficient_frontier.R pkg/PortfolioAnalytics/man/PortfolioAnalytics-package.Rd Log: /s/chart.Weights.EF/chart.EF.Weights to avoid clashing with other S3 method chart.Weights.* bump version to match rev number Modified: pkg/PortfolioAnalytics/DESCRIPTION =================================================================== --- pkg/PortfolioAnalytics/DESCRIPTION 2015-02-08 00:25:24 UTC (rev 3597) +++ pkg/PortfolioAnalytics/DESCRIPTION 2015-02-08 00:57:59 UTC (rev 3598) @@ -11,7 +11,7 @@ , person(given="Guy",family="Yollin",role="ctb") , person(given="R. Douglas",family="Martin",role="ctb") ) -Version: 0.9.3585 +Version: 0.9.3598 Date: $Date$ Maintainer: Brian G. Peterson Description: Portfolio optimization and analysis routines and graphics. Modified: pkg/PortfolioAnalytics/NAMESPACE =================================================================== --- pkg/PortfolioAnalytics/NAMESPACE 2015-02-08 00:25:24 UTC (rev 3597) +++ pkg/PortfolioAnalytics/NAMESPACE 2015-02-08 00:57:59 UTC (rev 3598) @@ -19,8 +19,8 @@ S3method(chart.Weights,optimize.portfolio.pso) S3method(chart.Weights,optimize.portfolio.random) S3method(chart.Weights,optimize.portfolio.rebalancing) -S3method(chart.Weights.EF,efficient.frontier) -S3method(chart.Weights.EF,optimize.portfolio) +S3method(chart.EF.Weights,efficient.frontier) +S3method(chart.EF.Weights,optimize.portfolio) S3method(extractObjectiveMeasures,opt.list) S3method(extractObjectiveMeasures,opt.rebal.list) S3method(extractObjectiveMeasures,optimize.portfolio) @@ -94,7 +94,7 @@ export(chart.RiskBudget) export(chart.RiskReward) export(chart.Weights) -export(chart.Weights.EF) +export(chart.EF.Weights) export(combine.optimizations) export(combine.portfolios) export(constrained_objective) Modified: pkg/PortfolioAnalytics/R/charts.efficient.frontier.R =================================================================== --- pkg/PortfolioAnalytics/R/charts.efficient.frontier.R 2015-02-08 00:25:24 UTC (rev 3597) +++ pkg/PortfolioAnalytics/R/charts.efficient.frontier.R 2015-02-08 00:57:59 UTC (rev 3598) @@ -286,17 +286,17 @@ #' @param element.color provides the color for drawing less-important chart elements, such as the box lines, axis lines, etc. #' @param legend.loc NULL, "topright", "right", or "bottomright". If legend.loc is NULL, the legend will not be plotted. #' @author Ross Bennett -#' @rdname chart.Weights.EF +#' @rdname chart.EF.Weights #' @export -chart.Weights.EF <- function(object, ...){ - UseMethod("chart.Weights.EF") +chart.EF.Weights <- function(object, ...){ + UseMethod("chart.EF.Weights") } -#' @rdname chart.Weights.EF -#' @method chart.Weights.EF efficient.frontier -#' @S3method chart.Weights.EF efficient.frontier -chart.Weights.EF.efficient.frontier <- function(object, ..., colorset=NULL, n.portfolios=25, by.groups=FALSE, match.col="ES", main="", cex.lab=0.8, cex.axis=0.8, cex.legend=0.8, legend.labels=NULL, element.color="darkgray", legend.loc="topright"){ +#' @rdname chart.EF.Weights +#' @method chart.EF.Weights efficient.frontier +#' @S3method chart.EF.Weights efficient.frontier +chart.EF.Weights.efficient.frontier <- function(object, ..., colorset=NULL, n.portfolios=25, by.groups=FALSE, match.col="ES", main="", cex.lab=0.8, cex.axis=0.8, cex.legend=0.8, legend.labels=NULL, element.color="darkgray", legend.loc="topright"){ # using ideas from weightsPlot.R in fPortfolio package if(!inherits(object, "efficient.frontier")) stop("object must be of class 'efficient.frontier'") @@ -418,16 +418,16 @@ box(col=element.color) } -#' @rdname chart.Weights.EF -#' @method chart.Weights.EF optimize.portfolio -#' @S3method chart.Weights.EF optimize.portfolio -chart.Weights.EF.optimize.portfolio <- function(object, ..., colorset=NULL, n.portfolios=25, by.groups=FALSE, match.col="ES", main="", cex.lab=0.8, cex.axis=0.8, cex.legend=0.8, legend.labels=NULL, element.color="darkgray", legend.loc="topright"){ +#' @rdname chart.EF.Weights +#' @method chart.EF.Weights optimize.portfolio +#' @S3method chart.EF.Weights optimize.portfolio +chart.EF.Weights.optimize.portfolio <- function(object, ..., colorset=NULL, n.portfolios=25, by.groups=FALSE, match.col="ES", main="", cex.lab=0.8, cex.axis=0.8, cex.legend=0.8, legend.labels=NULL, element.color="darkgray", legend.loc="topright"){ # chart the weights along the efficient frontier of an objected created by optimize.portfolio if(!inherits(object, "optimize.portfolio")) stop("object must be of class optimize.portfolio") frontier <- extractEfficientFrontier(object=object, match.col=match.col, n.portfolios=n.portfolios) - chart.Weights.EF(object=frontier, colorset=colorset, ..., + chart.EF.Weights(object=frontier, colorset=colorset, ..., match.col=match.col, by.groups=by.groups, main=main, cex.lab=cex.lab, cex.axis=cex.axis, cex.legend=cex.legend, legend.labels=legend.labels, element.color=element.color, Modified: pkg/PortfolioAnalytics/demo/demo_efficient_frontier.R =================================================================== --- pkg/PortfolioAnalytics/demo/demo_efficient_frontier.R 2015-02-08 00:25:24 UTC (rev 3597) +++ pkg/PortfolioAnalytics/demo/demo_efficient_frontier.R 2015-02-08 00:57:59 UTC (rev 3598) @@ -70,19 +70,19 @@ tangent.line=FALSE, labels.assets=FALSE, pch.assets=1) #' Chart the asset weights along the efficient frontier. -chart.Weights.EF(meanvar.ef, colorset=bluemono, match.col="StdDev") +chart.EF.Weights(meanvar.ef, colorset=bluemono, match.col="StdDev") #' Chart the group weights along the efficient frontier. -chart.Weights.EF(meanvar.ef, colorset=bluemono, by.groups=TRUE, match.col="StdDev") +chart.EF.Weights(meanvar.ef, colorset=bluemono, by.groups=TRUE, match.col="StdDev") #' The labels for Mean, Weight, and StdDev can be increased or decreased with #' the cex.lab argument. The default is cex.lab=0.8. -chart.Weights.EF(meanvar.ef, colorset=bluemono, match.col="StdDev", main="", cex.lab=1) +chart.EF.Weights(meanvar.ef, colorset=bluemono, match.col="StdDev", main="", cex.lab=1) #' If you have a lot of assets and they don't fit with the default legend, you #' can set legend.loc=NULL and customize the plot. par(mar=c(8, 4, 4, 2)+0.1, xpd=TRUE) -chart.Weights.EF(meanvar.ef, colorset=bluemono, match.col="StdDev", legend.loc=NULL) +chart.EF.Weights(meanvar.ef, colorset=bluemono, match.col="StdDev", legend.loc=NULL) legend("bottom", legend=colnames(R), inset=-1, fill=bluemono, bty="n", ncol=3, cex=0.8) par(mar=c(5, 4, 4, 2)+0.1, xpd=FALSE) @@ -105,9 +105,9 @@ #' The weights along the efficient frontier can be plotted by passing in the #' optimize.portfolio output object. -chart.Weights.EF(opt_meanvar, match.col="StdDev") +chart.EF.Weights(opt_meanvar, match.col="StdDev") -chart.Weights.EF(opt_meanvar, match.col="StdDev", by.groups=TRUE) +chart.EF.Weights(opt_meanvar, match.col="StdDev", by.groups=TRUE) #' Extract the efficient frontier and then plot it. #' Note that if you want to do multiple charts of the efficient frontier from @@ -116,8 +116,8 @@ ef <- extractEfficientFrontier(object=opt_meanvar, match.col="StdDev", n.portfolios=15) ef summary(ef, digits=5) -chart.Weights.EF(ef, match.col="StdDev", colorset=bluemono) -chart.Weights.EF(ef, match.col="StdDev", colorset=bluemono, by.groups=TRUE) +chart.EF.Weights(ef, match.col="StdDev", colorset=bluemono) +chart.EF.Weights(ef, match.col="StdDev", colorset=bluemono, by.groups=TRUE) #' Compute the mean-ES efficient frontier. meanetl.ef <- create.EfficientFrontier(R=R, portfolio=init, type="mean-ES") @@ -127,14 +127,14 @@ #' Chart the mean-ES efficient frontier. chart.EfficientFrontier(meanetl.ef, match.col="ES", main="mean-ETL Efficient Frontier", type="l", col="blue", RAR.text="STARR") -chart.Weights.EF(meanetl.ef, colorset=bluemono, match.col="ES") -chart.Weights.EF(meanetl.ef, by.groups=TRUE, colorset=bluemono, match.col="ES") +chart.EF.Weights(meanetl.ef, colorset=bluemono, match.col="ES") +chart.EF.Weights(meanetl.ef, by.groups=TRUE, colorset=bluemono, match.col="ES") #' Compute the mean-ES efficient frontier using random portfolios to solve #' the optimization problem. meanetl.rp.ef <- create.EfficientFrontier(R=R, portfolio=meanetl.portf, type="random", match.col="ES") chart.EfficientFrontier(meanetl.rp.ef, match.col="ES", main="mean-ETL RP Efficient Frontier", type="l", col="blue", rf=0) -chart.Weights.EF(meanetl.rp.ef, colorset=bluemono, match.col="ES") +chart.EF.Weights(meanetl.rp.ef, colorset=bluemono, match.col="ES") # mean-etl efficient frontier with optimize.portfolio output opt_meanetl <- optimize.portfolio(R=R, portfolio=meanetl.portf, optimize_method="random", search_size=2000, trace=TRUE) Modified: pkg/PortfolioAnalytics/man/PortfolioAnalytics-package.Rd =================================================================== --- pkg/PortfolioAnalytics/man/PortfolioAnalytics-package.Rd 2015-02-08 00:25:24 UTC (rev 3597) +++ pkg/PortfolioAnalytics/man/PortfolioAnalytics-package.Rd 2015-02-08 00:57:59 UTC (rev 3598) @@ -84,7 +84,7 @@ \code{\link{chart.Weights}} plots the weights of the optimal portfolio. \code{\link{chart.RiskReward}} plots the optimal portfolio in risk-reward space. The random portfolios, DEoptim, and pso solvers will return trace portfolio information at each iteration when \code{\link{optimize.portfolio}} is run with \code{trace=TRUE}. If this is the case, \code{\link{chart.RiskReward}} will plot these portfolios so that the feasible space can be easily visualized. Although the GenSA and ROI solvers do not return trace portfolio information, random portfolios can be be generated with the argument \code{rp=TRUE} in \code{\link{chart.RiskReward}}. A \code{plot} function is provided that will plot the weights and risk-reward scatter chart. The component risk contribution can be charted for portfolio optimization problems with risk budget objectives with \code{\link{chart.RiskBudget}}. Neighbor portfolios can be plotted in \code{\link{chart.RiskBudget}}, \code{\link{chart.Weights}}, and \code{\link{chart.RiskReward}}. -Efficient frontiers can be extracted from \code{optimize.portfolio} objects or created from a \code{portfolio} object. The efficient frontier can be charted in risk-reward space with \code{\link{chart.EfficientFrontier}}. The weights along the efficient frontier can be charted with \code{\link{chart.Weights.EF}}. +Efficient frontiers can be extracted from \code{optimize.portfolio} objects or created from a \code{portfolio} object. The efficient frontier can be charted in risk-reward space with \code{\link{chart.EfficientFrontier}}. The weights along the efficient frontier can be charted with \code{\link{chart.EF.Weights}}. Multiple objects created via \code{\link{optimize.portfolio}} can be combined with \code{\link{combine.optimizations}} for visual comparison. The weights of the optimal portfolios can be plotted with \code{\link{chart.Weights}}. The optimal portfolios can be compared in risk-reward space with \code{\link{chart.RiskReward}}. The portfolio component risk contributions of the multiple optimal portfolios can be plotted with \code{\link{chart.RiskBudget}}. } Added: pkg/PortfolioAnalytics/man/chart.EF.Weights.Rd =================================================================== --- pkg/PortfolioAnalytics/man/chart.EF.Weights.Rd (rev 0) +++ pkg/PortfolioAnalytics/man/chart.EF.Weights.Rd 2015-02-08 00:57:59 UTC (rev 3598) @@ -0,0 +1,54 @@ +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/charts.efficient.frontier.R +\name{chart.EF.Weights} +\alias{chart.EF.Weights} +\alias{chart.EF.Weights.efficient.frontier} +\alias{chart.EF.Weights.optimize.portfolio} +\title{Chart weights along an efficient frontier} +\usage{ +chart.EF.Weights(object, ...) + +\method{chart.EF.Weights}{efficient.frontier}(object, ..., colorset = NULL, + n.portfolios = 25, by.groups = FALSE, match.col = "ES", main = "", + cex.lab = 0.8, cex.axis = 0.8, cex.legend = 0.8, legend.labels = NULL, + element.color = "darkgray", legend.loc = "topright") + +\method{chart.EF.Weights}{optimize.portfolio}(object, ..., colorset = NULL, + n.portfolios = 25, by.groups = FALSE, match.col = "ES", main = "", + cex.lab = 0.8, cex.axis = 0.8, cex.legend = 0.8, legend.labels = NULL, + element.color = "darkgray", legend.loc = "topright") +} +\arguments{ +\item{object}{object of class \code{efficient.frontier} or \code{optimize.portfolio}.} + +\item{colorset}{color palette or vector of colors to use.} + +\item{n.portfolios}{number of portfolios to extract along the efficient frontier.} + +\item{by.groups}{TRUE/FALSE. If TRUE, the group weights are charted.} + +\item{match.col}{string name of column to use for risk (horizontal axis). Must match the name of an objective.} + +\item{main}{title used in the plot.} + +\item{cex.lab}{the magnification to be used for x-axis and y-axis labels relative to the current setting of 'cex'.} + +\item{cex.axis}{the magnification to be used for sizing the axis text relative to the current setting of 'cex', similar to \code{\link{plot}}.} + +\item{cex.legend}{the magnification to be used for sizing the legend relative to the current setting of 'cex', similar to \code{\link{plot}}.} + +\item{legend.labels}{character vector to use for the legend labels.} + +\item{element.color}{provides the color for drawing less-important chart elements, such as the box lines, axis lines, etc.} + +\item{legend.loc}{NULL, "topright", "right", or "bottomright". If legend.loc is NULL, the legend will not be plotted.} + +\item{\dots}{passthru parameters to \code{barplot}.} +} +\description{ +This function produces a stacked barplot of weights along an efficient frontier. +} +\author{ +Ross Bennett +} + Deleted: pkg/PortfolioAnalytics/man/chart.Weights.EF.Rd =================================================================== --- pkg/PortfolioAnalytics/man/chart.Weights.EF.Rd 2015-02-08 00:25:24 UTC (rev 3597) +++ pkg/PortfolioAnalytics/man/chart.Weights.EF.Rd 2015-02-08 00:57:59 UTC (rev 3598) @@ -1,54 +0,0 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/charts.efficient.frontier.R -\name{chart.Weights.EF} -\alias{chart.Weights.EF} -\alias{chart.Weights.EF.efficient.frontier} -\alias{chart.Weights.EF.optimize.portfolio} -\title{Chart weights along an efficient frontier} -\usage{ -chart.Weights.EF(object, ...) - -\method{chart.Weights.EF}{efficient.frontier}(object, ..., colorset = NULL, - n.portfolios = 25, by.groups = FALSE, match.col = "ES", main = "", - cex.lab = 0.8, cex.axis = 0.8, cex.legend = 0.8, legend.labels = NULL, - element.color = "darkgray", legend.loc = "topright") - -\method{chart.Weights.EF}{optimize.portfolio}(object, ..., colorset = NULL, - n.portfolios = 25, by.groups = FALSE, match.col = "ES", main = "", - cex.lab = 0.8, cex.axis = 0.8, cex.legend = 0.8, legend.labels = NULL, - element.color = "darkgray", legend.loc = "topright") -} -\arguments{ -\item{object}{object of class \code{efficient.frontier} or \code{optimize.portfolio}.} - -\item{colorset}{color palette or vector of colors to use.} - -\item{n.portfolios}{number of portfolios to extract along the efficient frontier.} - -\item{by.groups}{TRUE/FALSE. If TRUE, the group weights are charted.} - -\item{match.col}{string name of column to use for risk (horizontal axis). Must match the name of an objective.} - -\item{main}{title used in the plot.} - -\item{cex.lab}{the magnification to be used for x-axis and y-axis labels relative to the current setting of 'cex'.} - -\item{cex.axis}{the magnification to be used for sizing the axis text relative to the current setting of 'cex', similar to \code{\link{plot}}.} - -\item{cex.legend}{the magnification to be used for sizing the legend relative to the current setting of 'cex', similar to \code{\link{plot}}.} - -\item{legend.labels}{character vector to use for the legend labels.} - -\item{element.color}{provides the color for drawing less-important chart elements, such as the box lines, axis lines, etc.} - -\item{legend.loc}{NULL, "topright", "right", or "bottomright". If legend.loc is NULL, the legend will not be plotted.} - -\item{\dots}{passthru parameters to \code{barplot}.} -} -\description{ -This function produces a stacked barplot of weights along an efficient frontier. -} -\author{ -Ross Bennett -} - From noreply at r-forge.r-project.org Sun Feb 8 02:33:35 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 8 Feb 2015 02:33:35 +0100 (CET) Subject: [Returnanalytics-commits] r3599 - in pkg/PortfolioAnalytics: . man Message-ID: <20150208013335.74ED01875DE@r-forge.r-project.org> Author: rossbennett34 Date: 2015-02-08 02:33:35 +0100 (Sun, 08 Feb 2015) New Revision: 3599 Modified: pkg/PortfolioAnalytics/DESCRIPTION pkg/PortfolioAnalytics/man/indexes.Rd Log: remove empty sections from indexes.Rd Modified: pkg/PortfolioAnalytics/DESCRIPTION =================================================================== --- pkg/PortfolioAnalytics/DESCRIPTION 2015-02-08 00:57:59 UTC (rev 3598) +++ pkg/PortfolioAnalytics/DESCRIPTION 2015-02-08 01:33:35 UTC (rev 3599) @@ -11,7 +11,7 @@ , person(given="Guy",family="Yollin",role="ctb") , person(given="R. Douglas",family="Martin",role="ctb") ) -Version: 0.9.3598 +Version: 0.9.3599 Date: $Date$ Maintainer: Brian G. Peterson Description: Portfolio optimization and analysis routines and graphics. Modified: pkg/PortfolioAnalytics/man/indexes.Rd =================================================================== --- pkg/PortfolioAnalytics/man/indexes.Rd 2015-02-08 00:57:59 UTC (rev 3598) +++ pkg/PortfolioAnalytics/man/indexes.Rd 2015-02-08 01:33:35 UTC (rev 3599) @@ -6,9 +6,6 @@ The indexes are: US Bonds, US Equities, International Equities, Commodities, US T-Bills, and Inflation} \usage{data(indexes)} \format{CSV converted into xts object with montly observations} -\details{ } -\source{ } -\references{ } \examples{ data(indexes) From noreply at r-forge.r-project.org Mon Feb 9 21:05:44 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 9 Feb 2015 21:05:44 +0100 (CET) Subject: [Returnanalytics-commits] r3600 - in pkg/FactorAnalytics: . R man Message-ID: <20150209200544.A79A31876F2@r-forge.r-project.org> Author: chenyian Date: 2015-02-09 21:05:44 +0100 (Mon, 09 Feb 2015) New Revision: 3600 Added: pkg/FactorAnalytics/R/fitTsfmUpDn.r pkg/FactorAnalytics/man/fitTsfmUpDn.Rd Modified: pkg/FactorAnalytics/NAMESPACE pkg/FactorAnalytics/R/fitTsfmLagBeta.r pkg/FactorAnalytics/R/fitTsfmMT.r pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd pkg/FactorAnalytics/man/fitTsfmMT.Rd Log: The first version of fitTsfmUpDn.r. It is a wrapper function of fitTsfm.r and returns a list object containing "Up" and "Dn". Both are class of "Tsfm". Modified: pkg/FactorAnalytics/NAMESPACE =================================================================== --- pkg/FactorAnalytics/NAMESPACE 2015-02-08 01:33:35 UTC (rev 3599) +++ pkg/FactorAnalytics/NAMESPACE 2015-02-09 20:05:44 UTC (rev 3600) @@ -32,6 +32,7 @@ export(fitTsfm) export(fitTsfmMT) export(fitTsfmLagBeta) +export(fitTsfmUpDn) export(fmCov) export(fmEsDecomp) export(fmSdDecomp) Modified: pkg/FactorAnalytics/R/fitTsfmLagBeta.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmLagBeta.r 2015-02-08 01:33:35 UTC (rev 3599) +++ pkg/FactorAnalytics/R/fitTsfmLagBeta.r 2015-02-09 20:05:44 UTC (rev 3600) @@ -58,8 +58,8 @@ #' @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 mkt.name name of the column for market excess returns (Rm-Rf); this -#' is necessary to add market timing factors. Default is NULL. +#' @param mkt.name name of the column for market excess returns (Rm-Rf). It +#' is required for a lagged Betas factor model. #' @param rf.name name of the column of risk free rate variable to calculate #' excess returns for all assets (in \code{asset.names}) and factors (in #' \code{factor.names}). Default is NULL, and no action is taken. @@ -142,7 +142,7 @@ #' # load data from the database #' data(managers) #' -#' # example: Market-timing factors with OLS fit +#' # example: A lagged Beetas model with OLS fit #' fit <- fitTsfmLagBeta(asset.names=colnames(managers[,(1:6)]),LagBeta=2, #' factor.names="SP500.TR",mkt.name="SP500.TR", #' rf.name="US.3m.TR",data=managers) Modified: pkg/FactorAnalytics/R/fitTsfmMT.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmMT.r 2015-02-08 01:33:35 UTC (rev 3599) +++ pkg/FactorAnalytics/R/fitTsfmMT.r 2015-02-09 20:05:44 UTC (rev 3600) @@ -58,8 +58,8 @@ #' @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 mkt.name name of the column for market excess returns (Rm-Rf); this -#' is necessary to add market timing factors. Default is NULL. +#' @param mkt.name name of the column for market excess returns (Rm-Rf); It +#' is required for a market timing model. #' @param rf.name name of the column of risk free rate variable to calculate #' excess returns for all assets (in \code{asset.names}) and factors (in #' \code{factor.names}). Default is NULL, and no action is taken. Added: pkg/FactorAnalytics/R/fitTsfmUpDn.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmUpDn.r (rev 0) +++ pkg/FactorAnalytics/R/fitTsfmUpDn.r 2015-02-09 20:05:44 UTC (rev 3600) @@ -0,0 +1,205 @@ +#' @title Fit a up and down market factor model using time series regression +#' +#' @description This is a wrapper function to fits a up/down market model for one +#' or more 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 compute excess returns. +#' +#' Estimation method "OLS" corresponds to ordinary least squares using +#' \code{\link[stats]{lm}}, "DLS" is discounted least squares (weighted least +#' squares with exponentially declining weights that sum to unity), and, +#' "Robust" is robust regression (using \code{\link[robust]{lmRob}}). +#' +#' If \code{variable.selection="none"}, uses all the factors and performs no +#' variable selection. Whereas, "stepwise" performs traditional stepwise +#' LS or Robust regression (using \code{\link[stats]{step}} or +#' \code{\link[robust]{step.lmRob}}), that starts from the initial set of +#' factors and adds/subtracts factors only if the regression fit, as measured +#' by the Bayesian Information Criterion (BIC) or Akaike Information Criterion +#' (AIC), improves. And, "subsets" enables subsets selection using +#' \code{\link[leaps]{regsubsets}}; chooses the best performing subset of any +#' given size or within a range of subset sizes. Different methods such as +#' exhaustive search (default), forward or backward stepwise, or sequential +#' replacement can be employed.See \code{\link{fitTsfm.control}} for more +#' details on the control arguments. +#' +#' \code{variable.selection="lars"} corresponds to least angle regression +#' using \code{\link[lars]{lars}} with variants "lasso" (default), "lar", +#' "stepwise" or "forward.stagewise". Note: If \code{variable.selection="lars"}, +#' \code{fit.method} will be ignored. +#' +#' +#' \subsection{Data Processing}{ +#' +#' Note about NAs: Before model fitting, incomplete cases are removed for +#' every asset (return data combined with respective factors' return data) +#' using \code{\link[stats]{na.omit}}. Otherwise, all observations in +#' \code{data} are included. +#' +#' Note about \code{asset.names} and \code{factor.names}: Spaces in column +#' names of \code{data} will be converted to periods as \code{fitTsfm} works +#' with \code{xts} objects internally and colnames won't be left as they are. +#' } +#' +#' @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 mkt.name name of the column for market excess returns (Rm-Rf). It +#' is required for a up/down market model. +#' @param rf.name name of the column of risk free rate variable to calculate +#' excess returns for all assets (in \code{asset.names}) and factors (in +#' \code{factor.names}). Default is NULL, and no action is taken. +#' @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{mkt.name} and \code{rf.name}. +#' @param fit.method the estimation method, one of "OLS", "DLS" or "Robust". +#' See details. Default is "OLS". +#' @param variable.selection the variable selection method, one of "none", +#' "stepwise","subsets","lars". See details. Default is "none". +#' \code{mkt.name} is required if any of these options are to be implemented. +#' @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}} +#' +#' @return +#' +#' fitTsfmUpDn returns a list object containing \code{Up} and \code{Dn}. +#' Both \code{Up} and \code{Dn} are class of \code{"tsfm"}. +#' +#' fitTsfm returns an object of class \code{"tsfm"} for which +#' \code{print}, \code{plot}, \code{predict} and \code{summary} methods exist. +#' +#' The generic accessor functions \code{coef}, \code{fitted} and +#' \code{residuals} extract various useful features of the fit object. +#' Additionally, \code{fmCov} computes the covariance matrix for asset returns +#' based on the fitted factor model +#' +#' 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}{length-N vector of estimated alphas.} +#' \item{beta}{N x K matrix 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 +#' \code{variable.selection="lars"}} +#' \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 Yi-An Chen. +#' +#' @references +#' Christopherson, J. A., Carino, D. R., & Ferson, W. E. (2009). Portfolio +#' performance measurement and benchmarking. McGraw Hill Professional. +#' +#' Efron, B., Hastie, T., Johnstone, I., & Tibshirani, R. (2004). Least angle +#' regression. The Annals of statistics, 32(2), 407-499. +#' +#' Hastie, T., Tibshirani, R., Friedman, J., Hastie, T., Friedman, J., & +#' Tibshirani, R. (2009). The elements of statistical learning (Vol. 2, No. 1). +#' New York: Springer. +#' +#' Henriksson, R. D., & Merton, R. C. (1981). On market timing and investment +#' performance. II. Statistical procedures for evaluating forecasting skills. +#' Journal of business, 513-533. +#' +#' Treynor, J., & Mazuy, K. (1966). Can mutual funds outguess the market. +#' Harvard business review, 44(4), 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[stats]{fitted}}, \code{\link[stats]{residuals}}, +#' \code{\link{fmCov}}, \code{\link{fmSdDecomp}}, \code{\link{fmVaRDecomp}} +#' and \code{\link{fmEsDecomp}}. +#' +#' \code{\link{paFm}} for Performance Attribution. +#' +#' @examples +#' # load data from the database +#' data(managers) +#' +#' # example: Up and down market factor model with OLS fit +#' fitUpDn <- fitTsfmUpDn(asset.names=colnames(managers[,(1:6)]),mkt.name="SP500.TR", +#' data=managers, fit.method="OLS",control=NULL) +#' # List object +#' fitUpDn +#' +#' summary(fitUpDn$Up) +#' summary(fitUpDn$Dn) +#' +#' @importFrom PerformanceAnalytics checkData +#' @importFrom robust lmRob step.lmRob +#' @importFrom leaps regsubsets +#' @importFrom lars lars cv.lars +#' +#' @export + + +fitTsfmUpDn <- function(asset.names, factor.names=NULL, mkt.name=NULL, rf.name=NULL, + data=data, fit.method=c("OLS","DLS","Robust"), + variable.selection=c("none","stepwise","subsets","lars"), + control=fitTsfm.control(...),...) { + + if (is.null(mkt.name)){ + stop("Missing argument: mkt.name has to be specified for up and down market model.") + } + + + + factor.names <- union(factor.names,mkt.name) + + # convert data into an xts object and hereafter work with xts objects + data.xts <- checkData(data) + # convert index to 'Date' format for uniformity + time(data.xts) <- as.Date(time(data.xts)) + + # 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)))) + warning("Up market is defined as the excess Market returns is no less than 0.") + } else { + warning("Up market is defined as the Market returns is no less than 0.") + } + + mkt <- dat.xts[,mkt.name] + # up market + dataUp.xts <- dat.xts[mkt >= 0] + + fitUp <- fitTsfm(asset.names=asset.names,factor.names=factor.names,mkt.name=mkt.name,rf.name=rf.name, + data=dataUp.xts,fit.method=fit.method,variable.selection=variable.selection, + control=control) + + + # down market + dataDn.xts <- dat.xts[mkt < 0] + fitDn <- fitTsfm(asset.names=asset.names,factor.names=factor.names,mkt.name=mkt.name,rf.name=rf.name, + data=dataDn.xts,fit.method=fit.method,variable.selection=variable.selection, + control=control) + +return(list(Up = fitUp, Dn = fitDn)) +} Modified: pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd 2015-02-08 01:33:35 UTC (rev 3599) +++ pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd 2015-02-09 20:05:44 UTC (rev 3600) @@ -15,8 +15,8 @@ \item{factor.names}{vector containing names of the macroeconomic factors.} -\item{mkt.name}{name of the column for market excess returns (Rm-Rf); this -is necessary to add market timing factors. Default is NULL.} +\item{mkt.name}{name of the column for market excess returns (Rm-Rf). It +is required for a lagged Betas factor model.} \item{rf.name}{name of the column of risk free rate variable to calculate excess returns for all assets (in \code{asset.names}) and factors (in @@ -132,7 +132,7 @@ # load data from the database data(managers) -# example: Market-timing factors with OLS fit +# example: A lagged Beetas model with OLS fit fit <- fitTsfmLagBeta(asset.names=colnames(managers[,(1:6)]),LagBeta=2, factor.names="SP500.TR",mkt.name="SP500.TR", rf.name="US.3m.TR",data=managers) Modified: pkg/FactorAnalytics/man/fitTsfmMT.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfmMT.Rd 2015-02-08 01:33:35 UTC (rev 3599) +++ pkg/FactorAnalytics/man/fitTsfmMT.Rd 2015-02-09 20:05:44 UTC (rev 3600) @@ -15,8 +15,8 @@ \item{factor.names}{vector containing names of the macroeconomic factors.} -\item{mkt.name}{name of the column for market excess returns (Rm-Rf); this -is necessary to add market timing factors. Default is NULL.} +\item{mkt.name}{name of the column for market excess returns (Rm-Rf); It +is required for a market timing model.} \item{rf.name}{name of the column of risk free rate variable to calculate excess returns for all assets (in \code{asset.names}) and factors (in Added: pkg/FactorAnalytics/man/fitTsfmUpDn.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfmUpDn.Rd (rev 0) +++ pkg/FactorAnalytics/man/fitTsfmUpDn.Rd 2015-02-09 20:05:44 UTC (rev 3600) @@ -0,0 +1,170 @@ +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/fitTsfmUpDn.r +\name{fitTsfmUpDn} +\alias{fitTsfmUpDn} +\title{Fit a up and down market factor model using time series regression} +\usage{ +fitTsfmUpDn(asset.names, factor.names = NULL, mkt.name = NULL, + rf.name = NULL, data = data, fit.method = c("OLS", "DLS", "Robust"), + variable.selection = c("none", "stepwise", "subsets", "lars"), + control = fitTsfm.control(...), ...) +} +\arguments{ +\item{asset.names}{vector containing names of assets, whose returns or +excess returns are the dependent variable.} + +\item{factor.names}{vector containing names of the macroeconomic factors.} + +\item{mkt.name}{name of the column for market excess returns (Rm-Rf). It +is required for a up/down market model.} + +\item{rf.name}{name of the column of risk free rate variable to calculate +excess returns for all assets (in \code{asset.names}) and factors (in +\code{factor.names}). Default is NULL, and no action is taken.} + +\item{data}{vector, matrix, data.frame, xts, timeSeries or zoo object +containing column(s) named in \code{asset.names}, \code{factor.names} and +optionally, \code{mkt.name} and \code{rf.name}.} + +\item{fit.method}{the estimation method, one of "OLS", "DLS" or "Robust". +See details. Default is "OLS".} + +\item{variable.selection}{the variable selection method, one of "none", +"stepwise","subsets","lars". See details. Default is "none". +\code{mkt.name} is required if any of these options are to be implemented.} + +\item{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.} + +\item{...}{arguments passed to \code{\link{fitTsfm.control}}} +} +\value{ +fitTsfmUpDn returns a list object containing \code{Up} and \code{Dn}. +Both \code{Up} and \code{Dn} are class of \code{"tsfm"}. + +fitTsfm returns an object of class \code{"tsfm"} for which +\code{print}, \code{plot}, \code{predict} and \code{summary} methods exist. + +The generic accessor functions \code{coef}, \code{fitted} and +\code{residuals} extract various useful features of the fit object. +Additionally, \code{fmCov} computes the covariance matrix for asset returns +based on the fitted factor model + +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}{length-N vector of estimated alphas.} +\item{beta}{N x K matrix 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 +\code{variable.selection="lars"}} +\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. +} +\description{ +This is a wrapper function to fits a up/down market model for one +or more 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 compute excess returns. + +Estimation method "OLS" corresponds to ordinary least squares using +\code{\link[stats]{lm}}, "DLS" is discounted least squares (weighted least +squares with exponentially declining weights that sum to unity), and, +"Robust" is robust regression (using \code{\link[robust]{lmRob}}). + +If \code{variable.selection="none"}, uses all the factors and performs no +variable selection. Whereas, "stepwise" performs traditional stepwise +LS or Robust regression (using \code{\link[stats]{step}} or +\code{\link[robust]{step.lmRob}}), that starts from the initial set of +factors and adds/subtracts factors only if the regression fit, as measured +by the Bayesian Information Criterion (BIC) or Akaike Information Criterion +(AIC), improves. And, "subsets" enables subsets selection using +\code{\link[leaps]{regsubsets}}; chooses the best performing subset of any +given size or within a range of subset sizes. Different methods such as +exhaustive search (default), forward or backward stepwise, or sequential +replacement can be employed.See \code{\link{fitTsfm.control}} for more +details on the control arguments. + +\code{variable.selection="lars"} corresponds to least angle regression +using \code{\link[lars]{lars}} with variants "lasso" (default), "lar", +"stepwise" or "forward.stagewise". Note: If \code{variable.selection="lars"}, +\code{fit.method} will be ignored. + + +\subsection{Data Processing}{ + +Note about NAs: Before model fitting, incomplete cases are removed for +every asset (return data combined with respective factors' return data) +using \code{\link[stats]{na.omit}}. Otherwise, all observations in +\code{data} are included. + +Note about \code{asset.names} and \code{factor.names}: Spaces in column +names of \code{data} will be converted to periods as \code{fitTsfm} works +with \code{xts} objects internally and colnames won't be left as they are. +} +} +\examples{ +# load data from the database +data(managers) + +# example: Up and down market factor model with OLS fit +fitUpDn <- fitTsfmUpDn(asset.names=colnames(managers[,(1:6)]),mkt.name="SP500.TR", + data=managers, fit.method="OLS",control=NULL) + # List object + fitUpDn + + summary(fitUpDn$Up) + summary(fitUpDn$Dn) +} +\author{ +Yi-An Chen. +} +\references{ +Christopherson, J. A., Carino, D. R., & Ferson, W. E. (2009). Portfolio +performance measurement and benchmarking. McGraw Hill Professional. + +Efron, B., Hastie, T., Johnstone, I., & Tibshirani, R. (2004). Least angle +regression. The Annals of statistics, 32(2), 407-499. + +Hastie, T., Tibshirani, R., Friedman, J., Hastie, T., Friedman, J., & +Tibshirani, R. (2009). The elements of statistical learning (Vol. 2, No. 1). +New York: Springer. + +Henriksson, R. D., & Merton, R. C. (1981). On market timing and investment +performance. II. Statistical procedures for evaluating forecasting skills. +Journal of business, 513-533. + +Treynor, J., & Mazuy, K. (1966). Can mutual funds outguess the market. +Harvard business review, 44(4), 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[stats]{fitted}}, \code{\link[stats]{residuals}}, +\code{\link{fmCov}}, \code{\link{fmSdDecomp}}, \code{\link{fmVaRDecomp}} +and \code{\link{fmEsDecomp}}. + +\code{\link{paFm}} for Performance Attribution. +} + From noreply at r-forge.r-project.org Mon Feb 23 23:57:04 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 23 Feb 2015 23:57:04 +0100 (CET) Subject: [Returnanalytics-commits] r3601 - in pkg/FactorAnalytics: . R man Message-ID: <20150223225704.E491A187700@r-forge.r-project.org> Author: chenyian Date: 2015-02-23 23:57:04 +0100 (Mon, 23 Feb 2015) New Revision: 3601 Added: pkg/FactorAnalytics/R/summary.tsfmUpDn.r pkg/FactorAnalytics/man/summary.tsfmUpDn.Rd Modified: pkg/FactorAnalytics/NAMESPACE pkg/FactorAnalytics/R/fitTsfmUpDn.r Log: Add summary.tsfmUpDn.r method and print.summary.tsfmUpDn.r method Modified: pkg/FactorAnalytics/NAMESPACE =================================================================== --- pkg/FactorAnalytics/NAMESPACE 2015-02-09 20:05:44 UTC (rev 3600) +++ pkg/FactorAnalytics/NAMESPACE 2015-02-23 22:57:04 UTC (rev 3601) @@ -21,12 +21,14 @@ S3method(print,sfm) S3method(print,summary.sfm) S3method(print,summary.tsfm) +S3method(print,summary.tsfmUpDn) S3method(print,tsfm) S3method(residuals,sfm) S3method(residuals,tsfm) S3method(summary,pafm) S3method(summary,sfm) S3method(summary,tsfm) +S3method(summary,tsfmUpDn) export(dCornishFisher) export(fitSfm) export(fitTsfm) Modified: pkg/FactorAnalytics/R/fitTsfmUpDn.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmUpDn.r 2015-02-09 20:05:44 UTC (rev 3600) +++ pkg/FactorAnalytics/R/fitTsfmUpDn.r 2015-02-23 22:57:04 UTC (rev 3601) @@ -201,5 +201,7 @@ data=dataDn.xts,fit.method=fit.method,variable.selection=variable.selection, control=control) -return(list(Up = fitUp, Dn = fitDn)) + result <- list(Up = fitUp, Dn = fitDn) + class(result) <- "tsfmUpDn" +return(result) } Added: pkg/FactorAnalytics/R/summary.tsfmUpDn.r =================================================================== --- pkg/FactorAnalytics/R/summary.tsfmUpDn.r (rev 0) +++ pkg/FactorAnalytics/R/summary.tsfmUpDn.r 2015-02-23 22:57:04 UTC (rev 3601) @@ -0,0 +1,92 @@ +#' @title Summarizing a fitted up and down market time series factor model +#' +#' @description \code{summary} method for object of class \code{tsfmUpDn}. +#' Returned object is of class {summary.tsfmUpDn}. This function provides a \code{summary} +#' method to an object returned by a wrapper function \code{fitTsfmUpDn}. +#' +#' @details Since \code{fitTsfmUpDn} fits both up market and down market, +#' \code{summary.tsfmUpDn} applies \code{summary.tsfm} for both markets fitted +#' objects and combines the coefficients interested together. +#' +#' +#' @param object an object of class \code{tsfmUpDn} returned by \code{fitTsfmUpDn}. +#' @param ... futher arguments passed to or from \code{summary.tsfm} methods. +#' @param uD.list an object of class \code{summary.tsfmUpDn}. +#' @param digits number of significants digits to use when printing. +#' Default is 3. +#' +#' @return Returns an object of class \code{summary.tsfmUpDn}. This object contains +#' a list object of \code{Up} and \code{Dn} for up market and down market respectively. +#' +#' The print method for class \code{summary.tsfmUpDn} outputs the call, +#' coefficients (with standard errors and t-statistics), r-squared and +#' residual volatilty (under the homoskedasticity assumption) for all assets in up and +#' down market. +#' +#' Object of class \code{summary.tsfmUpDn} is a list of 2 containing: +#' \item{Up}{A list of the up market fitted object. It is a class of \code{summary.tsfm}} +#' \item{Dn}{A list of the down market fitted object. It is a class of \code{summary.tsfm}} +#' +#' @author Yi-An Chen. +#' +#' @seealso \code{\link{fitTsfmUpDn}}, \code{\link[stats]{summary.tsfm}} +#' +#' @examples +#' # load data from the database +#' data(managers) +#' +#' # example: Up and down market factor model with OLS fit +#' fitUpDn <- fitTsfmUpDn(asset.names=colnames(managers[,(1:6)]),mkt.name="SP500.TR", +#' data=managers, fit.method="OLS",control=NULL) +#' +#' summary(fitUpDn) +#' +#' @importFrom lmtest coeftest.default +#' @importFrom sandwich vcovHC.default vcovHAC.default +#' +#' @method summary tsfmUpDn +#' @export + +summary.tsfmUpDn <- function(object,...) { + # check input object validity + if (!inherits(object, "tsfmUpDn")) { + stop("Invalid 'tsfmUpDn' object") + } + uD.list <- lapply(object,summary,...) + class(uD.list) <- "summary.tsfmUpDn" + return(uD.list) +} + #' @rdname summary.tsfmUpDn + #' @method print summary.tsfmUpDn + #' @export + + + print.summary.tsfmUpDn <- function(uD.list, digits=3, ...) { + if(!is.null(cl <- uD.list$Up$call)) { + cat("\nCall:\n") + dput(cl) + } + cat("\nFactor Model Coefficients:\n", sep="") + n <- length(uD.list$Up$sum.list) + for (i in 1:n) { + options(digits = digits) + table.coef.Up <- (uD.list$Up$sum.list)[[i]]$coefficients + rownames(table.coef.Up) <- sapply(rownames(table.coef.Up),function(x) paste(x,"_Up",sep="") ) + table.coef.Dn <- (uD.list$Dn$sum.list)[[i]]$coefficients + rownames(table.coef.Dn) <- sapply(rownames(table.coef.Dn),function(x) paste(x,"_Dn",sep="") ) + table.coef <- rbind(table.coef.Up,table.coef.Dn) + if (dim(table.coef)[2] > 1) { + cat("\nAsset", i, ": ", names(uD.list$Up$sum.list[i]), "\n(", uD.list$Up$se.type, + " Standard Errors & T-stats)\n\n", sep="") + } else { + cat("\nAsset", i, ": ", names(uD.list$Up$sum.list[i]), "\n\n", sep="") + } + r2Up <- uD.list$Up$sum.list[[i]]$r.squared + sigmaUp <- uD.list$Up$sum.list[[i]]$sigma + r2Dn <- uD.list$Dn$sum.list[[i]]$r.squared + sigmaDn <- uD.list$Dn$sum.list[[i]]$sigma + printCoefmat(table.coef, digits=digits,...) + cat("\n R-squared_Up: ", r2Up,", Residual Volatility_Up: ", sigmaUp,"\n", + "R-squared_Dn: ", r2Dn,", Residual Volatility_Dn: ", sigmaDn) + } +} \ No newline at end of file Added: pkg/FactorAnalytics/man/summary.tsfmUpDn.Rd =================================================================== --- pkg/FactorAnalytics/man/summary.tsfmUpDn.Rd (rev 0) +++ pkg/FactorAnalytics/man/summary.tsfmUpDn.Rd 2015-02-23 22:57:04 UTC (rev 3601) @@ -0,0 +1,61 @@ +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/summary.tsfmUpDn.r +\name{summary.tsfmUpDn} +\alias{print.summary.tsfmUpDn} +\alias{summary.tsfmUpDn} +\title{Summarizing a fitted up and down market time series factor model} +\usage{ +\method{summary}{tsfmUpDn}(object, ...) + +\method{print}{summary.tsfmUpDn}(uD.list, digits = 3, ...) +} +\arguments{ +\item{object}{an object of class \code{tsfmUpDn} returned by \code{fitTsfmUpDn}.} + +\item{...}{futher arguments passed to or from \code{summary.tsfm} methods.} + +\item{uD.list}{an object of class \code{summary.tsfmUpDn}.} + +\item{digits}{number of significants digits to use when printing. +Default is 3.} +} +\value{ +Returns an object of class \code{summary.tsfmUpDn}. This object contains +a list object of \code{Up} and \code{Dn} for up market and down market respectively. + +The print method for class \code{summary.tsfmUpDn} outputs the call, +coefficients (with standard errors and t-statistics), r-squared and +residual volatilty (under the homoskedasticity assumption) for all assets in up and +down market. + +Object of class \code{summary.tsfmUpDn} is a list of 2 containing: +\item{Up}{A list of the up market fitted object. It is a class of \code{summary.tsfm}} +\item{Dn}{A list of the down market fitted object. It is a class of \code{summary.tsfm}} +} +\description{ +\code{summary} method for object of class \code{tsfmUpDn}. +Returned object is of class {summary.tsfmUpDn}. This function provides a \code{summary} +method to a return object of a wrapper function \code{fitTsfmUpDn}. +} +\details{ +Since \code{fitTsfmUpDn} fits both up market and down market, +\code{summary.tsfmUpDn} applies \code{summary.tsfm} for both markets fitted +objects and combines the coefficients together. +} +\examples{ +# load data from the database +data(managers) + +# example: Up and down market factor model with OLS fit +fitUpDn <- fitTsfmUpDn(asset.names=colnames(managers[,(1:6)]),mkt.name="SP500.TR", + data=managers, fit.method="OLS",control=NULL) + + summary(fitUpDn) +} +\author{ +Yi-An Chen. +} +\seealso{ +\code{\link{fitTsfmUpDn}}, \code{\link[stats]{summary.tsfm}} +} + From noreply at r-forge.r-project.org Tue Feb 24 00:18:47 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 24 Feb 2015 00:18:47 +0100 (CET) Subject: [Returnanalytics-commits] r3602 - in pkg/FactorAnalytics: . R man Message-ID: <20150223231847.411C3187700@r-forge.r-project.org> Author: chenyian Date: 2015-02-24 00:18:46 +0100 (Tue, 24 Feb 2015) New Revision: 3602 Added: pkg/FactorAnalytics/R/print.tsfmUpDn.r pkg/FactorAnalytics/man/print.tsfmUpDn.Rd Modified: pkg/FactorAnalytics/NAMESPACE pkg/FactorAnalytics/R/summary.tsfmUpDn.r pkg/FactorAnalytics/man/summary.tsfmUpDn.Rd Log: Add print.tsfmUpDn.r and print.tsfmUpDn.Rd Modified: pkg/FactorAnalytics/NAMESPACE =================================================================== --- pkg/FactorAnalytics/NAMESPACE 2015-02-23 22:57:04 UTC (rev 3601) +++ pkg/FactorAnalytics/NAMESPACE 2015-02-23 23:18:46 UTC (rev 3602) @@ -23,6 +23,7 @@ S3method(print,summary.tsfm) S3method(print,summary.tsfmUpDn) S3method(print,tsfm) +S3method(print,tsfmUpDn) S3method(residuals,sfm) S3method(residuals,tsfm) S3method(summary,pafm) Added: pkg/FactorAnalytics/R/print.tsfmUpDn.r =================================================================== --- pkg/FactorAnalytics/R/print.tsfmUpDn.r (rev 0) +++ pkg/FactorAnalytics/R/print.tsfmUpDn.r 2015-02-23 23:18:46 UTC (rev 3602) @@ -0,0 +1,62 @@ +#' @title Prints out a fitted up and down market time series factor model object +#' +#' @description S3 \code{print} method for object of class \code{tsfmUpDn}. Prints +#' the call, factor model dimension, regression coefficients, r-squared and +#' residual volatilities from the fitted object. +#' +#' @param x an object of class \code{tsfmUpDn} produced by \code{fitTsfmUpDn}. +#' @param digits an integer value, to indicate the required number of +#' significant digits. Default is 3. +#' @param ... optional arguments passed to the \code{print} method. +#' +#' @author Yi-An Chen and Sangeetha Srinivasan +#' +#' @seealso \code{\link{fitTsfmUpDn}}, \code{\link{summary.tsfmUpDn}} +#' +#' @examples +#' data(managers) +#' # example: Up and down market factor model with OLS fit +#' fitUpDn <- fitTsfmUpDn(asset.names=colnames(managers[,(1:6)]),mkt.name="SP500.TR", +#' data=managers, fit.method="OLS",control=NULL) +#' +#' print(fitUpDn) +#' +#' @method print tsfmUpDn +#' @export +#' + + + +print.tsfmUpDn <- function(x, digits=max(3, .Options$digits - 3), ...){ + if(!is.null(cl <- x$Up$call)){ + cat("\nCall:\n") + dput(cl) + } + cat("\nModel dimensions:\n") + tmp <- c(dim(t(x$Up$beta)), nrow(x$Up$data)) + names(tmp) <- c("Factors", "Assets", "Periods") + print(tmp) + cat("\nRegression Alphas in up market:\n") + print(t(x$Up$alpha), digits=digits,...) + cat("\nRegression Alphas in down market:\n") + print(t(x$Dn$alpha), digits=digits,...) + + cat("\nFactor Betas in up market:\n") + B <- as.matrix(t(x$Up$beta)) + if (x$Up$variable.selection=="lars") { B[B==0] <- NA } + print(B, digits=digits, na.print=".", ...) + cat("\nFactor Betas in down market:\n") + B <- as.matrix(t(x$Dn$beta)) + if (x$Dn$variable.selection=="lars") { B[B==0] <- NA } + print(B, digits=digits, na.print=".", ...) + + cat("\nR-squared values in up market:\n") + print(x$Up$r2, digits=digits, ...) + cat("\nR-squared values in down market:\n") + print(x$Dn$r2, digits=digits, ...) + + cat("\nResidual Volatilities in up market:\n") + print(x$Up$resid.sd, digits=digits, ...) + cat("\nResidual Volatilities in down market:\n") + print(x$Dn$resid.sd, digits=digits, ...) +} \ No newline at end of file Modified: pkg/FactorAnalytics/R/summary.tsfmUpDn.r =================================================================== --- pkg/FactorAnalytics/R/summary.tsfmUpDn.r 2015-02-23 22:57:04 UTC (rev 3601) +++ pkg/FactorAnalytics/R/summary.tsfmUpDn.r 2015-02-23 23:18:46 UTC (rev 3602) @@ -27,7 +27,7 @@ #' \item{Up}{A list of the up market fitted object. It is a class of \code{summary.tsfm}} #' \item{Dn}{A list of the down market fitted object. It is a class of \code{summary.tsfm}} #' -#' @author Yi-An Chen. +#' @author Yi-An Chen and Sangeetha Srinivasan. #' #' @seealso \code{\link{fitTsfmUpDn}}, \code{\link[stats]{summary.tsfm}} #' Added: pkg/FactorAnalytics/man/print.tsfmUpDn.Rd =================================================================== --- pkg/FactorAnalytics/man/print.tsfmUpDn.Rd (rev 0) +++ pkg/FactorAnalytics/man/print.tsfmUpDn.Rd 2015-02-23 23:18:46 UTC (rev 3602) @@ -0,0 +1,36 @@ +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/print.tsfmUpDn.r +\name{print.tsfmUpDn} +\alias{print.tsfmUpDn} +\title{Prints out a fitted up and down market time series factor model object} +\usage{ +\method{print}{tsfmUpDn}(x, digits = max(3, .Options$digits - 3), ...) +} +\arguments{ +\item{x}{an object of class \code{tsfmUpDn} produced by \code{fitTsfmUpDn}.} + +\item{digits}{an integer value, to indicate the required number of +significant digits. Default is 3.} + +\item{...}{optional arguments passed to the \code{print} method.} +} +\description{ +S3 \code{print} method for object of class \code{tsfmUpDn}. Prints +the call, factor model dimension, regression coefficients, r-squared and +residual volatilities from the fitted object. +} +\examples{ +data(managers) +# example: Up and down market factor model with OLS fit +fitUpDn <- fitTsfmUpDn(asset.names=colnames(managers[,(1:6)]),mkt.name="SP500.TR", + data=managers, fit.method="OLS",control=NULL) + +print(fitUpDn) +} +\author{ +Yi-An Chen and Sangeetha Srinivasan +} +\seealso{ +\code{\link{fitTsfmUpDn}}, \code{\link{summary.tsfmUpDn}} +} + Modified: pkg/FactorAnalytics/man/summary.tsfmUpDn.Rd =================================================================== --- pkg/FactorAnalytics/man/summary.tsfmUpDn.Rd 2015-02-23 22:57:04 UTC (rev 3601) +++ pkg/FactorAnalytics/man/summary.tsfmUpDn.Rd 2015-02-23 23:18:46 UTC (rev 3602) @@ -35,12 +35,12 @@ \description{ \code{summary} method for object of class \code{tsfmUpDn}. Returned object is of class {summary.tsfmUpDn}. This function provides a \code{summary} -method to a return object of a wrapper function \code{fitTsfmUpDn}. +method to an object returned by a wrapper function \code{fitTsfmUpDn}. } \details{ Since \code{fitTsfmUpDn} fits both up market and down market, \code{summary.tsfmUpDn} applies \code{summary.tsfm} for both markets fitted -objects and combines the coefficients together. +objects and combines the coefficients interested together. } \examples{ # load data from the database @@ -53,7 +53,7 @@ summary(fitUpDn) } \author{ -Yi-An Chen. +Yi-An Chen and Sangeetha Srinivasan. } \seealso{ \code{\link{fitTsfmUpDn}}, \code{\link[stats]{summary.tsfm}} From noreply at r-forge.r-project.org Tue Feb 24 01:02:16 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 24 Feb 2015 01:02:16 +0100 (CET) Subject: [Returnanalytics-commits] r3603 - pkg/FactorAnalytics Message-ID: <20150224000216.599411861E5@r-forge.r-project.org> Author: chenyian Date: 2015-02-24 01:02:15 +0100 (Tue, 24 Feb 2015) New Revision: 3603 Modified: pkg/FactorAnalytics/NAMESPACE Log: update NAMESPACE Modified: pkg/FactorAnalytics/NAMESPACE =================================================================== --- pkg/FactorAnalytics/NAMESPACE 2015-02-23 23:18:46 UTC (rev 3602) +++ pkg/FactorAnalytics/NAMESPACE 2015-02-24 00:02:15 UTC (rev 3603) @@ -17,6 +17,7 @@ S3method(plot,tsfm) S3method(predict,sfm) S3method(predict,tsfm) +S3method(predict,tsfmUpDn) S3method(print,pafm) S3method(print,sfm) S3method(print,summary.sfm) From noreply at r-forge.r-project.org Tue Feb 24 01:03:47 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 24 Feb 2015 01:03:47 +0100 (CET) Subject: [Returnanalytics-commits] r3604 - in pkg/FactorAnalytics: R man Message-ID: <20150224000347.8947018651F@r-forge.r-project.org> Author: chenyian Date: 2015-02-24 01:03:47 +0100 (Tue, 24 Feb 2015) New Revision: 3604 Added: pkg/FactorAnalytics/R/predict.tsfmUpDn.r pkg/FactorAnalytics/man/predict.tsfmUpDn.Rd Log: Add predict.tsfmUpDn.r and predict.tsfmUpDn.Rd Added: pkg/FactorAnalytics/R/predict.tsfmUpDn.r =================================================================== --- pkg/FactorAnalytics/R/predict.tsfmUpDn.r (rev 0) +++ pkg/FactorAnalytics/R/predict.tsfmUpDn.r 2015-02-24 00:03:47 UTC (rev 3604) @@ -0,0 +1,38 @@ +#' @title Predicts asset returns based on a fitted up and down market time series factor model +#' +#' @description S3 \code{predict} method for object of class \code{tsfmUpDn}. It +#' calls the \code{predict.tsfm} method for a list object of \code{Up} and \code{Dn} +#' +#' @param object an object of class \code{tsfmUpDn} produced by \code{fitTsfmUpDn}. +#' @param ... optional arguments passed to \code{predict.lm} or +#' \code{\link[robust]{predict.lmRob}}, such as \code{se.fit}, or, to +#' \code{\link[lars]{predict.lars}} such as \code{mode}. +#' +#' @return +#' \code{predict.tsfmUpDm} produces a list of \code{Up} and \code{Dn}. Both \code{Up} and \code{Dn} contain a +#' vector or a matrix of predictions. +#' +#' @author Yi-An Chen and Sangeetha Srinivasan +#' +#' @seealso \code{\link{predict.tsfm}},\code{\link{fitTsfmUpDn}}, \code{\link{summary.tsfmUpDn}} +#' +#' @examples +#' # load data from the database +#' data(managers) +#' # fit the factor model with OLS +# example: Up and down market factor model with OLS fit +#' fitUpDn <- fitTsfmUpDn(asset.names=colnames(managers[,(1:6)]),mkt.name="SP500.TR", +#' data=managers, fit.method="OLS",control=NULL) +#' +#' predict(fitUpDn) +#' +#' @importFrom PerformanceAnalytics checkData +#' +#' @method predict tsfmUpDn +#' @export +#' + +predict.tsfmUpDn <- function(object,...) { + uD.list <- lapply(object,predict,...) + return(uD.list) +} \ No newline at end of file Added: pkg/FactorAnalytics/man/predict.tsfmUpDn.Rd =================================================================== --- pkg/FactorAnalytics/man/predict.tsfmUpDn.Rd (rev 0) +++ pkg/FactorAnalytics/man/predict.tsfmUpDn.Rd 2015-02-24 00:03:47 UTC (rev 3604) @@ -0,0 +1,39 @@ +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/predict.tsfmUpDn.r +\name{predict.tsfmUpDn} +\alias{predict.tsfmUpDn} +\title{Predicts asset returns based on a fitted up and down market time series factor model} +\usage{ +\method{predict}{tsfmUpDn}(object, ...) +} +\arguments{ +\item{object}{an object of class \code{tsfmUpDn} produced by \code{fitTsfmUpDn}.} + +\item{...}{optional arguments passed to \code{predict.lm} or +\code{\link[robust]{predict.lmRob}}, such as \code{se.fit}, or, to +\code{\link[lars]{predict.lars}} such as \code{mode}.} +} +\value{ +\code{predict.tsfmUpDm} produces a list of \code{Up} and \code{Dn}. Both \code{Up} and \code{Dn} contain a +vector or a matrix of predictions. +} +\description{ +S3 \code{predict} method for object of class \code{tsfmUpDn}. It +calls the \code{predict.tsfm} method for a list object of \code{Up} and \code{Dn} +} +\examples{ +# load data from the database +data(managers) +# fit the factor model with OLS +fitUpDn <- fitTsfmUpDn(asset.names=colnames(managers[,(1:6)]),mkt.name="SP500.TR", + data=managers, fit.method="OLS",control=NULL) + +predict(fitUpDn) +} +\author{ +Yi-An Chen and Sangeetha Srinivasan +} +\seealso{ +\code{\link{predict.tsfm}},\code{\link{fitTsfmUpDn}}, \code{\link{summary.tsfmUpDn}} +} + From noreply at r-forge.r-project.org Tue Feb 24 02:37:13 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 24 Feb 2015 02:37:13 +0100 (CET) Subject: [Returnanalytics-commits] r3605 - in pkg/FactorAnalytics: . R man Message-ID: <20150224013713.EAE821878B0@r-forge.r-project.org> Author: chenyian Date: 2015-02-24 02:37:13 +0100 (Tue, 24 Feb 2015) New Revision: 3605 Added: pkg/FactorAnalytics/R/plot.tsfmUpDn.r pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd Modified: pkg/FactorAnalytics/NAMESPACE Log: Add plot.tsfmUpDn.r and plot.tsfmUpDn.Rd Modified: pkg/FactorAnalytics/NAMESPACE =================================================================== --- pkg/FactorAnalytics/NAMESPACE 2015-02-24 00:03:47 UTC (rev 3604) +++ pkg/FactorAnalytics/NAMESPACE 2015-02-24 01:37:13 UTC (rev 3605) @@ -15,6 +15,7 @@ S3method(plot,pafm) S3method(plot,sfm) S3method(plot,tsfm) +S3method(plot,tsfmUpDn) S3method(predict,sfm) S3method(predict,tsfm) S3method(predict,tsfmUpDn) Added: pkg/FactorAnalytics/R/plot.tsfmUpDn.r =================================================================== --- pkg/FactorAnalytics/R/plot.tsfmUpDn.r (rev 0) +++ pkg/FactorAnalytics/R/plot.tsfmUpDn.r 2015-02-24 01:37:13 UTC (rev 3605) @@ -0,0 +1,67 @@ +#' @title Plot actual against fitted values of up and down market time series factor model +#' +#' @description Generic \code{plot} method for object of class \code{tsfmUpDn}. +#' +#' @details +#' This method plots actual values against fitted value of up and down market time series +#' factor model. The black dots are actual values and the red lines are fitted values. +#' +#' For other types of plots, use the list objects (\code{Up} and \code{Dn}) of class \code{tsfmUpDn}. As a result, the +#' \code{plot.tsfm} can be applied. +#' +#' @param object an object of class \code{tsfmUpDn} produced by \code{fitTsfmUpDn}. +#' @param mkt.name The name of market returns used in \code{fitTsfmUpDn}. It is necessary +#' to provide the name of market returns. +#' @param assets.name The name of the assets used in \code{fitTsfmUpDn}. It only supports +#' single asset so far. +#' @param ... Other arguments can be used in \code{plot}. +#' @author Yi-An Chen +#' +#' @seealso \code{\link{fitTsfmUpDn}} +#' +#' @examples +#' +#' # load data from the database +#' data(managers) +#' # example: Up and down market factor model with OLS fit +#' fitUpDn <- fitTsfmUpDn(asset.names=colnames(managers[,(1:6)]),mkt.name="SP500.TR", +#' data=managers, fit.method="OLS",control=NULL) +#' # plot the fitted model of the first asset +#' plot(fitUpDn,mkt.name="SP500.TR",assets.name="HAM1") +#' +#' +#' @method plot tsfmUpDn +#' @export + + +plot.tsfmUpDn <- function(object,mkt.name,assets.name,...) { + + if (is.null(mkt.name)){ + stop("Missing argument: mkt.name has to be specified for plot method.") + } + + if (is.null(assets.name)){ + stop("Missing argument: assets.name has to be specified.") + } + + if (!(mkt.name %in% object$Up$factor.names)) { + stop("mkt.name has to the same mkt.name used in fitTsfmUpDn().") + } + + # extract info from the fitTsfm object + plotDataUp <- merge.xts(object$Up$data[,c(assets.name,mkt.name)], fitted(object$Up)[,assets.name]) + colnames(plotDataUp) <- c("ActualUp","MktUp","FittedUp") + plotDataDn <-merge.xts(object$Dn$data[,c(assets.name,mkt.name)], fitted(object$Dn)[,assets.name]) + colnames(plotDataDn) <- c("ActualDn","MktDn","FittedDn") + + plot(rbind(coredata(plotDataUp$MktUp),coredata(plotDataDn$MktDn)), + rbind(coredata(plotDataUp$ActualUp),coredata(plotDataDn$ActualDn)), + main = paste("Actual vs Fitted values of the Asset ",assets.name,sep=""), + xlab=mkt.name,ylab=assets.name,...) + abline(v=0) + lines(coredata(plotDataUp$MktUp),coredata(plotDataUp$FittedUp),col="red") + lines(coredata(plotDataDn$MktDn),coredata(plotDataDn$FittedDn),col="red") + abline(h=0) + + +} \ No newline at end of file Added: pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd =================================================================== --- pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd (rev 0) +++ pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd 2015-02-24 01:37:13 UTC (rev 3605) @@ -0,0 +1,45 @@ +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/plot.tsfmUpDn.r +\name{plot.tsfmUpDn} +\alias{plot.tsfmUpDn} +\title{Plot actual against fitted values of up and down market time series factor model} +\usage{ +\method{plot}{tsfmUpDn}(object, mkt.name, assets.name, ...) +} +\arguments{ +\item{object}{an object of class \code{tsfmUpDn} produced by \code{fitTsfmUpDn}.} + +\item{mkt.name}{The name of market returns used in \code{fitTsfmUpDn}. It is necessary +to provide the name of market returns.} + +\item{assets.name}{The name of the assets used in \code{fitTsfmUpDn}. It only supports +single asset so far.} + +\item{...}{Other arguments can be used in \code{plot}.} +} +\description{ +Generic \code{plot} method for object of class \code{tsfmUpDn}. +} +\details{ +This method plots actual values against fitted value of up and down market time series +factor model. The black dots are actual values and the red lines are fitted values. + +For other types of plots, use the list objects (\code{Up} and \code{Dn}) of class \code{tsfmUpDn}. As a result, the +\code{plot.tsfm} can be applied. +} +\examples{ +# load data from the database +data(managers) +# example: Up and down market factor model with OLS fit +fitUpDn <- fitTsfmUpDn(asset.names=colnames(managers[,(1:6)]),mkt.name="SP500.TR", + data=managers, fit.method="OLS",control=NULL) + # plot the fitted model of the first asset + plot(fitUpDn,mkt.name="SP500.TR",assets.name="HAM1") +} +\author{ +Yi-An Chen +} +\seealso{ +\code{\link{fitTsfmUpDn}} +} +