From noreply at r-forge.r-project.org Wed Mar 4 03:26:31 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 4 Mar 2015 03:26:31 +0100 (CET) Subject: [Returnanalytics-commits] r3606 - in pkg/PortfolioAnalytics: . R inst/tests sandbox Message-ID: <20150304022631.6B21618781F@r-forge.r-project.org> Author: rossbennett34 Date: 2015-03-04 03:26:30 +0100 (Wed, 04 Mar 2015) New Revision: 3606 Added: pkg/PortfolioAnalytics/sandbox/test_cplex_gmv.R pkg/PortfolioAnalytics/sandbox/test_cplex_maxMean.R pkg/PortfolioAnalytics/sandbox/test_cplex_minES.R pkg/PortfolioAnalytics/sandbox/test_cplex_qu.R Removed: pkg/PortfolioAnalytics/inst/tests/test_cplex_gmv.R pkg/PortfolioAnalytics/inst/tests/test_cplex_maxMean.R pkg/PortfolioAnalytics/inst/tests/test_cplex_minES.R pkg/PortfolioAnalytics/inst/tests/test_cplex_qu.R Modified: pkg/PortfolioAnalytics/DESCRIPTION pkg/PortfolioAnalytics/R/optimize.portfolio.R Log: removing support for ROI.plugin.cplex moved test scripts that use ROI.plugin.cplex and Rcplex to sandbox Modified: pkg/PortfolioAnalytics/DESCRIPTION =================================================================== --- pkg/PortfolioAnalytics/DESCRIPTION 2015-02-24 01:37:13 UTC (rev 3605) +++ pkg/PortfolioAnalytics/DESCRIPTION 2015-03-04 02:26:30 UTC (rev 3606) @@ -11,7 +11,7 @@ , person(given="Guy",family="Yollin",role="ctb") , person(given="R. Douglas",family="Martin",role="ctb") ) -Version: 0.9.3599 +Version: 0.9.3606 Date: $Date$ Maintainer: Brian G. Peterson Description: Portfolio optimization and analysis routines and graphics. @@ -32,7 +32,6 @@ ROI.plugin.glpk (>= 0.0.2), ROI.plugin.quadprog (>= 0.0.2), ROI.plugin.symphony (>= 0.0.2), - ROI.plugin.cplex (>= 0.0.2), pso, GenSA, corpcor, Modified: pkg/PortfolioAnalytics/R/optimize.portfolio.R =================================================================== --- pkg/PortfolioAnalytics/R/optimize.portfolio.R 2015-02-24 01:37:13 UTC (rev 3605) +++ pkg/PortfolioAnalytics/R/optimize.portfolio.R 2015-03-04 02:26:30 UTC (rev 3606) @@ -613,7 +613,7 @@ .formals <- formals(momentFUN) .formals <- modify.args(formals=.formals, arglist=list(...), dots=TRUE) # ** pass ROI=TRUE to set.portfolio.moments so the moments are not calculated - if(optimize_method %in% c("ROI", "quadprog", "glpk", "symphony", "ipop", "cplex")){ + if(optimize_method %in% c("ROI", "quadprog", "glpk", "symphony", "ipop")){ obj_names <- unlist(lapply(portfolio$objectives, function(x) x$name)) if(any(obj_names %in% c("CVaR", "ES", "ETL"))){ .formals <- modify.args(formals=.formals, arglist=list(ROI=TRUE), dots=TRUE) @@ -869,7 +869,7 @@ } ## end case for random - roi_solvers <- c("ROI", "quadprog", "glpk", "symphony", "ipop", "cplex") + roi_solvers <- c("ROI", "quadprog", "glpk", "symphony", "ipop") if(optimize_method %in% roi_solvers){ # check for a control argument for list of solver control arguments if(hasArg(control)) control=match.call(expand.dots=TRUE)$control else control=NULL Deleted: pkg/PortfolioAnalytics/inst/tests/test_cplex_gmv.R =================================================================== --- pkg/PortfolioAnalytics/inst/tests/test_cplex_gmv.R 2015-02-24 01:37:13 UTC (rev 3605) +++ pkg/PortfolioAnalytics/inst/tests/test_cplex_gmv.R 2015-03-04 02:26:30 UTC (rev 3606) @@ -1,166 +0,0 @@ -library(PortfolioAnalytics) -library(Rcplex) -library(ROI) -library(ROI.plugin.cplex) -library(testthat) - -# Test that PortfolioAnalytics with ROI.plugin.cplex solutions equal Rcplex solutions -context("GMV Portfolios: PortfolioAnalytics with ROI.plugin.cplex and Rcplex") - -# args(Rcplex) -# ?Rcplex - -##### Data ##### -data(edhec) -R <- edhec[, 1:5] -funds <- colnames(R) -m <- ncol(R) - -##### Parameters ##### -portf <- portfolio.spec(funds) -portf <- add.constraint(portf, type="full_investment") -portf <- add.constraint(portf, type="box", min=-Inf, max=Inf) -portf <- add.objective(portf, type="risk", name="var") - -# Quadratic part of objective function -objQ <- 2 * cov(R) - -# Linear part of objective function -objL <- rep(0, m) - -# Constraints matrix -Amat <- matrix(1, nrow=1, ncol=m) - -# right hand side of constraints -rhs <- 1 - -# direction of inequality of constraints -dir <- "E" - -##### Unconstrained ##### -# Upper and lower bounds (i.e. box constraints) -# Rcplex bounds -lb <- rep(-Inf, m) -ub <- rep(Inf, m) - -# Solve optimization with Rcplex -opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, - sense=dir, control=list(trace=0)) - -# Solve optimization with PortfolioAnalytics -opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") -weights <- as.numeric(extractWeights(opt.pa)) - -test_that("Unconstrained: PortfolioAnalytics and Rcplex solution weights are equal", { - expect_that(weights, equals(opt.rcplex$xopt)) -}) - -test_that("Unconstrained: PortfolioAnalytics and Rcplex solution objective values are equal", { - expect_that(opt.pa$out, equals(opt.rcplex$obj)) -}) - -##### Long Only ##### -# Upper and lower bounds (i.e. box constraints) -# Rcplex bounds -lb <- rep(0, m) -ub <- rep(1, m) - -# Update box constraints in portfolio -portf$constraints[[2]]$min <- lb -portf$constraints[[2]]$max <- ub - -# Solve optimization with Rcplex -opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, - sense=dir, control=list(trace=0)) - -# Solve optimization with PortfolioAnalytics -opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") -weights <- as.numeric(extractWeights(opt.pa)) - -test_that("Long Only: PortfolioAnalytics and Rcplex solution weights are equal", { - expect_that(weights, equals(opt.rcplex$xopt)) -}) - -test_that("Long Only: PortfolioAnalytics bounds are respected", { - expect_that(all(weights >= lb) & all(weights <= ub), is_true()) -}) - -test_that("Long Only: Rcplex bounds are respected", { - expect_that(all(opt.rcplex$xopt >= lb) & all(opt.rcplex$xopt <= ub), is_true()) -}) - -test_that("Long Only: PortfolioAnalytics and Rcplex solution objective values are equal", { - expect_that(opt.pa$out, equals(opt.rcplex$obj)) -}) - -##### Box ##### -# Upper and lower bounds (i.e. box constraints) -# Rcplex bounds -lb <- rep(0.05, m) -ub <- rep(0.55, m) - -# Update box constraints in portfolio -portf$constraints[[2]]$min <- lb -portf$constraints[[2]]$max <- ub - -# Solve optimization with Rcplex -opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, - sense=dir, control=list(trace=0)) - -# Solve optimization with PortfolioAnalytics -opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") -weights <- as.numeric(extractWeights(opt.pa)) - - -test_that("Box: PortfolioAnalytics and Rcplex solution weights are equal", { - expect_that(weights, equals(opt.rcplex$xopt)) -}) - -test_that("Box: PortfolioAnalytics bounds are respected", { - expect_that(all(weights >= lb) & all(weights <= ub), is_true()) -}) - -test_that("Box: Rcplex bounds are respected", { - expect_that(all(opt.rcplex$xopt >= lb) & all(opt.rcplex$xopt <= ub), is_true()) -}) - -test_that("Box: PortfolioAnalytics and Rcplex solution objective values are equal", { - expect_that(opt.pa$out, equals(opt.rcplex$obj)) -}) - -##### Box with Shorting ##### -# Upper and lower bounds (i.e. box constraints) -# Rcplex bounds -lb <- rep(-0.05, m) -ub <- rep(0.55, m) - -# Update box constraints in portfolio -portf$constraints[[2]]$min <- lb -portf$constraints[[2]]$max <- ub - -# Solve optimization with Rcplex -opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, - sense=dir, control=list(trace=0)) - -# Solve optimization with PortfolioAnalytics -opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") -weights <- as.numeric(extractWeights(opt.pa)) - - -test_that("Box with Shorting: PortfolioAnalytics and Rcplex solution weights are equal", { - expect_that(weights, equals(opt.rcplex$xopt)) -}) - -test_that("Box with Shorting: PortfolioAnalytics bounds are respected", { - expect_that(all(weights >= lb) & all(weights <= ub), is_true()) -}) - -test_that("Box with Shorting: Rcplex bounds are respected", { - expect_that(all(opt.rcplex$xopt >= lb) & all(opt.rcplex$xopt <= ub), is_true()) -}) - -test_that("Box with Shorting: PortfolioAnalytics and Rcplex solution objective values are equal", { - expect_that(opt.pa$out, equals(opt.rcplex$obj)) -}) - -Rcplex.close() Deleted: pkg/PortfolioAnalytics/inst/tests/test_cplex_maxMean.R =================================================================== --- pkg/PortfolioAnalytics/inst/tests/test_cplex_maxMean.R 2015-02-24 01:37:13 UTC (rev 3605) +++ pkg/PortfolioAnalytics/inst/tests/test_cplex_maxMean.R 2015-03-04 02:26:30 UTC (rev 3606) @@ -1,140 +0,0 @@ -library(PortfolioAnalytics) -library(Rcplex) -library(ROI) -library(ROI.plugin.cplex) -library(testthat) - -# Test that ROI.plugin.cplex solutions equal Rcplex solutions -context("Maximum Mean Return Portfolios: PortfolioAnalytics with ROI.plugin.cplex and Rcplex") - -# args(Rcplex) -# ?Rcplex - -##### Data ##### -data(edhec) -R <- edhec[, 1:5] -funds <- colnames(R) -m <- ncol(R) - -##### Parameters ##### -portf <- portfolio.spec(funds) -portf <- add.constraint(portf, type="full_investment") -portf <- add.constraint(portf, type="box", min=0, max=1) -portf <- add.objective(portf, type="return", name="mean") - -# Quadratic part of objective function -objQ <- NULL - -# Linear part of objective function -objL <- -colMeans(R) - -# Constraints matrix -Amat <- matrix(1, nrow=1, ncol=m) - -# right hand side of constraints -rhs <- 1 - -# direction of inequality of constraints -dir <- "E" - - -##### Long Only ##### -# Upper and lower bounds (i.e. box constraints) -# Rcplex bounds -lb <- rep(0, m) -ub <- rep(1, m) - -# Solve optimization with Rcplex -opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, - sense=dir, control=list(trace=0)) - -# Solve optimization with PortfolioAnalytics -opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") -weights <- as.numeric(extractWeights(opt.pa)) - -test_that("Long Only: PortfolioAnalytics and Rcplex solution weights are equal", { - expect_that(weights, equals(opt.rcplex$xopt)) -}) - -test_that("Long Only: PortfolioAnalytics bounds are respected", { - expect_that(all(weights >= lb) & all(weights <= ub), is_true()) -}) - -test_that("Long Only: Rcplex bounds are respected", { - expect_that(all(opt.rcplex$xopt >= lb) & all(opt.rcplex$xopt <= ub), is_true()) -}) - -test_that("Long Only: PortfolioAnalytics and Rcplex solution objective values are equal", { - expect_that(opt.pa$out, equals(opt.rcplex$obj)) -}) - -##### Box ##### -# Upper and lower bounds (i.e. box constraints) -# Rcplex bounds -lb <- rep(0.05, m) -ub <- rep(0.55, m) - -# Update box constraints in portfolio -portf$constraints[[2]]$min <- lb -portf$constraints[[2]]$max <- ub - -# Solve optimization with Rcplex -opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, - sense=dir, control=list(trace=0)) - -# Solve optimization with PortfolioAnalytics -opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") -weights <- as.numeric(extractWeights(opt.pa)) - -test_that("Box: PortfolioAnalytics and Rcplex solution weights are equal", { - expect_that(weights, equals(opt.rcplex$xopt)) -}) - -test_that("Box: PortfolioAnalytics bounds are respected", { - expect_that(all(weights >= lb) & all(weights <= ub), is_true()) -}) - -test_that("Box: Rcplex bounds are respected", { - expect_that(all(opt.rcplex$xopt >= lb) & all(opt.rcplex$xopt <= ub), is_true()) -}) - -test_that("Box: PortfolioAnalytics and Rcplex solution objective values are equal", { - expect_that(opt.pa$out, equals(opt.rcplex$obj)) -}) - -##### Box with Shorting ##### -# Upper and lower bounds (i.e. box constraints) -# Rcplex bounds -lb <- rep(-0.05, m) -ub <- rep(0.55, m) - -# Update box constraints in portfolio -portf$constraints[[2]]$min <- lb -portf$constraints[[2]]$max <- ub - -# Solve optimization with Rcplex -opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, - sense=dir, control=list(trace=0)) - -# Solve optimization with PortfolioAnalytics -opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") -weights <- as.numeric(extractWeights(opt.pa)) - -test_that("Box with Shorting: PortfolioAnalytics and Rcplex solution weights are equal", { - expect_that(weights, equals(opt.rcplex$xopt)) -}) - -test_that("Box with Shorting: PortfolioAnalytics bounds are respected", { - expect_that(all(weights >= lb) & all(weights <= ub), is_true()) -}) - -test_that("Box with Shorting: Rcplex bounds are respected", { - expect_that(all(opt.rcplex$xopt >= lb) & all(opt.rcplex$xopt <= ub), is_true()) -}) - -test_that("Box with Shorting: PortfolioAnalytics and Rcplex solution objective values are equal", { - expect_that(opt.pa$out, equals(opt.rcplex$obj)) -}) - -Rcplex.close() - Deleted: pkg/PortfolioAnalytics/inst/tests/test_cplex_minES.R =================================================================== --- pkg/PortfolioAnalytics/inst/tests/test_cplex_minES.R 2015-02-24 01:37:13 UTC (rev 3605) +++ pkg/PortfolioAnalytics/inst/tests/test_cplex_minES.R 2015-03-04 02:26:30 UTC (rev 3606) @@ -1,184 +0,0 @@ -library(PortfolioAnalytics) -library(Rcplex) -library(ROI) -library(ROI.plugin.cplex) -library(testthat) - -# Test that ROI.plugin.cplex solutions equal Rcplex solutions -context("Minimum ES Portfolios: PortfolioAnalytics with ROI.plugin.cplex and Rcplex") - -# args(Rcplex) -# ?Rcplex - -##### Data ##### -data(edhec) -R <- edhec[, 1:5] -funds <- colnames(R) - -##### Parameters ##### -m <- ncol(R) -n <- nrow(R) -alpha <- 0.05 - -portf <- portfolio.spec(funds) -portf <- add.constraint(portf, type="full_investment") -portf <- add.constraint(portf, type="box", min=-Inf, max=Inf) -portf <- add.objective(portf, type="risk", name="ES", arguments=list(p=1-alpha)) - -# Quadratic part of objective function -objQ <- NULL - -# Linear part of objective function -objL <- c(rep(0, m), rep(1 / (alpha * n), n), 1) - -# Constraints matrix -Amat <- cbind(rbind(1, zoo::coredata(R)), - rbind(0, cbind(diag(n), 1))) - -# right hand side of constraints -rhs <- c(1, rep(0, n)) - -# direction of inequality of constraints -dir <- c("E", rep("G", n)) - -##### Unconstrained ##### -# Upper and lower bounds (i.e. box constraints) -# Rcplex bounds -min_box <- rep(-Inf, m) -max_box <- rep(Inf, m) - -lb <- c(min_box, rep(0, n), -1) -ub <- c(max_box, rep(Inf, n), 1) - - -# Solve optimization with Rcplex -opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, - sense=dir, control=list(trace=0)) - -# Solve optimization with PortfolioAnalytics -opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") -weights <- as.numeric(extractWeights(opt.pa)) - - -test_that("Unconstrained: PortfolioAnalytics and Rcplex solution weights are equal", { - expect_that(weights, equals(opt.rcplex$xopt[1:m])) -}) - -test_that("Unconstrained: PortfolioAnalytics and Rcplex solution objective values are equal", { - expect_that(opt.pa$out, equals(opt.rcplex$obj)) -}) - - -##### Long Only ##### -# Upper and lower bounds (i.e. box constraints) -# Rcplex bounds -min_box <- rep(0, m) -max_box <- rep(1, m) - -lb <- c(min_box, rep(0, n), -1) -ub <- c(max_box, rep(Inf, n), 1) - -# Update box constraints in portfolio -portf$constraints[[2]]$min <- min_box -portf$constraints[[2]]$max <- max_box - -# Solve optimization with Rcplex -opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, - sense=dir, control=list(trace=0)) - -# Solve optimization with PortfolioAnalytics -opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") -weights <- as.numeric(extractWeights(opt.pa)) - -test_that("Long Only: PortfolioAnalytics and Rcplex solution weights are equal", { - expect_that(weights, equals(opt.rcplex$xopt[1:m])) -}) - -test_that("Long Only: PortfolioAnalytics bounds are respected", { - expect_that(all(weights >= min_box) & all(weights <= max_box), is_true()) -}) - -test_that("Long Only: Rcplex bounds are respected", { - expect_that(all(opt.rcplex$xopt[1:m] >= min_box) & all(opt.rcplex$xopt[1:m] <= max_box), is_true()) -}) - -test_that("Long Only: PortfolioAnalytics and Rcplex solution objective values are equal", { - expect_that(opt.pa$out, equals(opt.rcplex$obj)) -}) - -##### Box ##### -# Upper and lower bounds (i.e. box constraints) -# Rcplex bounds -min_box <- rep(0.05, m) -max_box <- rep(0.55, m) - -lb <- c(min_box, rep(0, n), -1) -ub <- c(max_box, rep(Inf, n), 1) - -# Update box constraints in portfolio -portf$constraints[[2]]$min <- min_box -portf$constraints[[2]]$max <- max_box - -# Solve optimization with Rcplex -opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, - sense=dir, control=list(trace=0)) - -# Solve optimization with PortfolioAnalytics -opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") -weights <- as.numeric(extractWeights(opt.pa)) - -test_that("Box: PortfolioAnalytics and Rcplex solution weights are equal", { - expect_that(weights, equals(opt.rcplex$xopt[1:m])) -}) - -test_that("Box: PortfolioAnalytics bounds are respected", { - expect_that(all(weights >= min_box) & all(weights <= max_box), is_true()) -}) - -test_that("Box: Rcplex bounds are respected", { - expect_that(all(opt.rcplex$xopt[1:m] >= min_box) & all(opt.rcplex$xopt[1:m] <= max_box), is_true()) -}) - -test_that("Box: PortfolioAnalytics and Rcplex solution objective values are equal", { - expect_that(opt.pa$out, equals(opt.rcplex$obj)) -}) - -##### Box with Shorting ##### -# Upper and lower bounds (i.e. box constraints) -# Rcplex bounds -min_box <- rep(-0.05, m) -max_box <- rep(0.55, m) - -lb <- c(min_box, rep(0, n), -1) -ub <- c(max_box, rep(Inf, n), 1) - -# Update box constraints in portfolio -portf$constraints[[2]]$min <- min_box -portf$constraints[[2]]$max <- max_box - -# Solve optimization with Rcplex -opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, - sense=dir, control=list(trace=0)) - -# Solve optimization with PortfolioAnalytics -opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") -weights <- as.numeric(extractWeights(opt.pa)) - -test_that("Box with Shorting: PortfolioAnalytics and Rcplex solution weights are equal", { - expect_that(weights, equals(opt.rcplex$xopt[1:m])) -}) - -test_that("Box with Shorting: PortfolioAnalytics bounds are respected", { - expect_that(all(weights >= min_box) & all(weights <= max_box), is_true()) -}) - -test_that("Box with Shorting: Rcplex bounds are respected", { - expect_that(all(opt.rcplex$xopt[1:m] >= min_box) & all(opt.rcplex$xopt[1:m] <= max_box), is_true()) -}) - -test_that("Box with Shorting: PortfolioAnalytics and Rcplex solution objective values are equal", { - expect_that(opt.pa$out, equals(opt.rcplex$obj)) -}) - -Rcplex.close() - Deleted: pkg/PortfolioAnalytics/inst/tests/test_cplex_qu.R =================================================================== --- pkg/PortfolioAnalytics/inst/tests/test_cplex_qu.R 2015-02-24 01:37:13 UTC (rev 3605) +++ pkg/PortfolioAnalytics/inst/tests/test_cplex_qu.R 2015-03-04 02:26:30 UTC (rev 3606) @@ -1,171 +0,0 @@ -library(PortfolioAnalytics) -library(Rcplex) -library(ROI) -library(ROI.plugin.cplex) -library(testthat) - -# Test that PortfolioAnalytics with ROI.plugin.cplex solutions equal Rcplex solutions -context("Maximum Quadratic Utility Portfolios: PortfolioAnalytics with ROI.plugin.cplex and Rcplex") - -# args(Rcplex) -# ?Rcplex - -##### Data ##### -data(edhec) -R <- edhec[, 1:5] -funds <- colnames(R) -m <- ncol(R) - -##### Parameters ##### - -# risk aversion parameter -lambda <- 1 - -portf <- portfolio.spec(funds) -portf <- add.constraint(portf, type="full_investment") -portf <- add.constraint(portf, type="box", min=-Inf, max=Inf) -portf <- add.objective(portf, type="risk", name="var", risk_aversion=lambda) -portf <- add.objective(portf, type="return", name="mean") - -# Quadratic part of objective function -objQ <- lambda * 2 * cov(R) - -# Linear part of objective function -objL <- -colMeans(R) - -# Constraints matrix -Amat <- matrix(1, nrow=1, ncol=m) - -# right hand side of constraints -rhs <- 1 - -# direction of inequality of constraints -dir <- "E" - -##### Unconstrained ##### -# Upper and lower bounds (i.e. box constraints) -# Rcplex bounds -lb <- rep(-Inf, m) -ub <- rep(Inf, m) - -# Solve optimization with Rcplex -opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, - sense=dir, control=list(trace=0)) - -# Solve optimization with PortfolioAnalytics -opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") -weights <- as.numeric(extractWeights(opt.pa)) - -test_that("Unconstrained: PortfolioAnalytics and Rcplex solution weights are equal", { - expect_that(weights, equals(opt.rcplex$xopt)) -}) - -test_that("Unconstrained: PortfolioAnalytics and Rcplex solution objective values are equal", { - expect_that(opt.pa$out, equals(opt.rcplex$obj)) -}) - -##### Long Only ##### -# Upper and lower bounds (i.e. box constraints) -# Rcplex bounds -lb <- rep(0, m) -ub <- rep(1, m) - -# Update box constraints in portfolio -portf$constraints[[2]]$min <- lb -portf$constraints[[2]]$max <- ub - -# Solve optimization with Rcplex -opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, - sense=dir, control=list(trace=0)) - -# Solve optimization with PortfolioAnalytics -opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") -weights <- as.numeric(extractWeights(opt.pa)) - -test_that("Long Only: PortfolioAnalytics and Rcplex solution weights are equal", { - expect_that(weights, equals(opt.rcplex$xopt)) -}) - -test_that("Long Only: PortfolioAnalytics bounds are respected", { - expect_that(all(weights >= lb) & all(weights <= ub), is_true()) -}) - -test_that("Long Only: Rcplex bounds are respected", { - expect_that(all(opt.rcplex$xopt >= lb) & all(opt.rcplex$xopt <= ub), is_true()) -}) - -test_that("Long Only: PortfolioAnalytics and Rcplex solution objective values are equal", { - expect_that(opt.pa$out, equals(opt.rcplex$obj)) -}) - -##### Box ##### -# Upper and lower bounds (i.e. box constraints) -# Rcplex bounds -lb <- rep(0.05, m) -ub <- rep(0.55, m) - -# Update box constraints in portfolio -portf$constraints[[2]]$min <- lb -portf$constraints[[2]]$max <- ub - -# Solve optimization with Rcplex -opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, - sense=dir, control=list(trace=0)) - -# Solve optimization with PortfolioAnalytics -opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") -weights <- as.numeric(extractWeights(opt.pa)) - - -test_that("Box: PortfolioAnalytics and Rcplex solution weights are equal", { - expect_that(weights, equals(opt.rcplex$xopt)) -}) - -test_that("Box: PortfolioAnalytics bounds are respected", { - expect_that(all(weights >= lb) & all(weights <= ub), is_true()) -}) - -test_that("Box: Rcplex bounds are respected", { - expect_that(all(opt.rcplex$xopt >= lb) & all(opt.rcplex$xopt <= ub), is_true()) -}) - -test_that("Box: PortfolioAnalytics and Rcplex solution objective values are equal", { - expect_that(opt.pa$out, equals(opt.rcplex$obj)) -}) - -##### Box with Shorting ##### -# Upper and lower bounds (i.e. box constraints) -# Rcplex bounds -lb <- rep(-0.05, m) -ub <- rep(0.55, m) - -# Update box constraints in portfolio -portf$constraints[[2]]$min <- lb -portf$constraints[[2]]$max <- ub - -# Solve optimization with Rcplex -opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, - sense=dir, control=list(trace=0)) - -# Solve optimization with PortfolioAnalytics -opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") -weights <- as.numeric(extractWeights(opt.pa)) - - -test_that("Box with Shorting: PortfolioAnalytics and Rcplex solution weights are equal", { - expect_that(weights, equals(opt.rcplex$xopt)) -}) - -test_that("Box with Shorting: PortfolioAnalytics bounds are respected", { - expect_that(all(weights >= lb) & all(weights <= ub), is_true()) -}) - -test_that("Box with Shorting: Rcplex bounds are respected", { - expect_that(all(opt.rcplex$xopt >= lb) & all(opt.rcplex$xopt <= ub), is_true()) -}) - -test_that("Box with Shorting: PortfolioAnalytics and Rcplex solution objective values are equal", { - expect_that(opt.pa$out, equals(opt.rcplex$obj)) -}) - -Rcplex.close() Added: pkg/PortfolioAnalytics/sandbox/test_cplex_gmv.R =================================================================== --- pkg/PortfolioAnalytics/sandbox/test_cplex_gmv.R (rev 0) +++ pkg/PortfolioAnalytics/sandbox/test_cplex_gmv.R 2015-03-04 02:26:30 UTC (rev 3606) @@ -0,0 +1,166 @@ +library(PortfolioAnalytics) +library(Rcplex) +library(ROI) +library(ROI.plugin.cplex) +library(testthat) + +# Test that PortfolioAnalytics with ROI.plugin.cplex solutions equal Rcplex solutions +context("GMV Portfolios: PortfolioAnalytics with ROI.plugin.cplex and Rcplex") + +# args(Rcplex) +# ?Rcplex + +##### Data ##### +data(edhec) +R <- edhec[, 1:5] +funds <- colnames(R) +m <- ncol(R) + +##### Parameters ##### +portf <- portfolio.spec(funds) +portf <- add.constraint(portf, type="full_investment") +portf <- add.constraint(portf, type="box", min=-Inf, max=Inf) +portf <- add.objective(portf, type="risk", name="var") + +# Quadratic part of objective function +objQ <- 2 * cov(R) + +# Linear part of objective function +objL <- rep(0, m) + +# Constraints matrix +Amat <- matrix(1, nrow=1, ncol=m) + +# right hand side of constraints +rhs <- 1 + +# direction of inequality of constraints +dir <- "E" + +##### Unconstrained ##### +# Upper and lower bounds (i.e. box constraints) +# Rcplex bounds +lb <- rep(-Inf, m) +ub <- rep(Inf, m) + +# Solve optimization with Rcplex +opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, + sense=dir, control=list(trace=0)) + +# Solve optimization with PortfolioAnalytics +opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") +weights <- as.numeric(extractWeights(opt.pa)) + +test_that("Unconstrained: PortfolioAnalytics and Rcplex solution weights are equal", { + expect_that(weights, equals(opt.rcplex$xopt)) +}) + +test_that("Unconstrained: PortfolioAnalytics and Rcplex solution objective values are equal", { + expect_that(opt.pa$out, equals(opt.rcplex$obj)) +}) + +##### Long Only ##### +# Upper and lower bounds (i.e. box constraints) +# Rcplex bounds +lb <- rep(0, m) +ub <- rep(1, m) + +# Update box constraints in portfolio +portf$constraints[[2]]$min <- lb +portf$constraints[[2]]$max <- ub + +# Solve optimization with Rcplex +opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, + sense=dir, control=list(trace=0)) + +# Solve optimization with PortfolioAnalytics +opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") +weights <- as.numeric(extractWeights(opt.pa)) + +test_that("Long Only: PortfolioAnalytics and Rcplex solution weights are equal", { + expect_that(weights, equals(opt.rcplex$xopt)) +}) + +test_that("Long Only: PortfolioAnalytics bounds are respected", { + expect_that(all(weights >= lb) & all(weights <= ub), is_true()) +}) + +test_that("Long Only: Rcplex bounds are respected", { + expect_that(all(opt.rcplex$xopt >= lb) & all(opt.rcplex$xopt <= ub), is_true()) +}) + +test_that("Long Only: PortfolioAnalytics and Rcplex solution objective values are equal", { + expect_that(opt.pa$out, equals(opt.rcplex$obj)) +}) + +##### Box ##### +# Upper and lower bounds (i.e. box constraints) +# Rcplex bounds +lb <- rep(0.05, m) +ub <- rep(0.55, m) + +# Update box constraints in portfolio +portf$constraints[[2]]$min <- lb +portf$constraints[[2]]$max <- ub + +# Solve optimization with Rcplex +opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, + sense=dir, control=list(trace=0)) + +# Solve optimization with PortfolioAnalytics +opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") +weights <- as.numeric(extractWeights(opt.pa)) + + +test_that("Box: PortfolioAnalytics and Rcplex solution weights are equal", { + expect_that(weights, equals(opt.rcplex$xopt)) +}) + +test_that("Box: PortfolioAnalytics bounds are respected", { + expect_that(all(weights >= lb) & all(weights <= ub), is_true()) +}) + +test_that("Box: Rcplex bounds are respected", { + expect_that(all(opt.rcplex$xopt >= lb) & all(opt.rcplex$xopt <= ub), is_true()) +}) + +test_that("Box: PortfolioAnalytics and Rcplex solution objective values are equal", { + expect_that(opt.pa$out, equals(opt.rcplex$obj)) +}) + +##### Box with Shorting ##### +# Upper and lower bounds (i.e. box constraints) +# Rcplex bounds +lb <- rep(-0.05, m) +ub <- rep(0.55, m) + +# Update box constraints in portfolio +portf$constraints[[2]]$min <- lb +portf$constraints[[2]]$max <- ub + +# Solve optimization with Rcplex +opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, + sense=dir, control=list(trace=0)) + +# Solve optimization with PortfolioAnalytics +opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") +weights <- as.numeric(extractWeights(opt.pa)) + + +test_that("Box with Shorting: PortfolioAnalytics and Rcplex solution weights are equal", { + expect_that(weights, equals(opt.rcplex$xopt)) +}) + +test_that("Box with Shorting: PortfolioAnalytics bounds are respected", { + expect_that(all(weights >= lb) & all(weights <= ub), is_true()) +}) + +test_that("Box with Shorting: Rcplex bounds are respected", { + expect_that(all(opt.rcplex$xopt >= lb) & all(opt.rcplex$xopt <= ub), is_true()) +}) + +test_that("Box with Shorting: PortfolioAnalytics and Rcplex solution objective values are equal", { + expect_that(opt.pa$out, equals(opt.rcplex$obj)) +}) + +Rcplex.close() Added: pkg/PortfolioAnalytics/sandbox/test_cplex_maxMean.R =================================================================== --- pkg/PortfolioAnalytics/sandbox/test_cplex_maxMean.R (rev 0) +++ pkg/PortfolioAnalytics/sandbox/test_cplex_maxMean.R 2015-03-04 02:26:30 UTC (rev 3606) @@ -0,0 +1,140 @@ +library(PortfolioAnalytics) +library(Rcplex) +library(ROI) +library(ROI.plugin.cplex) +library(testthat) + +# Test that ROI.plugin.cplex solutions equal Rcplex solutions +context("Maximum Mean Return Portfolios: PortfolioAnalytics with ROI.plugin.cplex and Rcplex") + +# args(Rcplex) +# ?Rcplex + +##### Data ##### +data(edhec) +R <- edhec[, 1:5] +funds <- colnames(R) +m <- ncol(R) + +##### Parameters ##### +portf <- portfolio.spec(funds) +portf <- add.constraint(portf, type="full_investment") +portf <- add.constraint(portf, type="box", min=0, max=1) +portf <- add.objective(portf, type="return", name="mean") + +# Quadratic part of objective function +objQ <- NULL + +# Linear part of objective function +objL <- -colMeans(R) + +# Constraints matrix +Amat <- matrix(1, nrow=1, ncol=m) + +# right hand side of constraints +rhs <- 1 + +# direction of inequality of constraints +dir <- "E" + + +##### Long Only ##### +# Upper and lower bounds (i.e. box constraints) +# Rcplex bounds +lb <- rep(0, m) +ub <- rep(1, m) + +# Solve optimization with Rcplex +opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, + sense=dir, control=list(trace=0)) + +# Solve optimization with PortfolioAnalytics +opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") +weights <- as.numeric(extractWeights(opt.pa)) + +test_that("Long Only: PortfolioAnalytics and Rcplex solution weights are equal", { + expect_that(weights, equals(opt.rcplex$xopt)) +}) + +test_that("Long Only: PortfolioAnalytics bounds are respected", { + expect_that(all(weights >= lb) & all(weights <= ub), is_true()) +}) + +test_that("Long Only: Rcplex bounds are respected", { + expect_that(all(opt.rcplex$xopt >= lb) & all(opt.rcplex$xopt <= ub), is_true()) +}) + +test_that("Long Only: PortfolioAnalytics and Rcplex solution objective values are equal", { + expect_that(opt.pa$out, equals(opt.rcplex$obj)) +}) + +##### Box ##### +# Upper and lower bounds (i.e. box constraints) +# Rcplex bounds +lb <- rep(0.05, m) +ub <- rep(0.55, m) + +# Update box constraints in portfolio +portf$constraints[[2]]$min <- lb +portf$constraints[[2]]$max <- ub + +# Solve optimization with Rcplex +opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, + sense=dir, control=list(trace=0)) + +# Solve optimization with PortfolioAnalytics +opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") +weights <- as.numeric(extractWeights(opt.pa)) + +test_that("Box: PortfolioAnalytics and Rcplex solution weights are equal", { + expect_that(weights, equals(opt.rcplex$xopt)) +}) + +test_that("Box: PortfolioAnalytics bounds are respected", { + expect_that(all(weights >= lb) & all(weights <= ub), is_true()) +}) + +test_that("Box: Rcplex bounds are respected", { + expect_that(all(opt.rcplex$xopt >= lb) & all(opt.rcplex$xopt <= ub), is_true()) +}) + +test_that("Box: PortfolioAnalytics and Rcplex solution objective values are equal", { + expect_that(opt.pa$out, equals(opt.rcplex$obj)) +}) + +##### Box with Shorting ##### +# Upper and lower bounds (i.e. box constraints) +# Rcplex bounds +lb <- rep(-0.05, m) +ub <- rep(0.55, m) + +# Update box constraints in portfolio +portf$constraints[[2]]$min <- lb +portf$constraints[[2]]$max <- ub + +# Solve optimization with Rcplex +opt.rcplex <- Rcplex(cvec=objL, Amat=Amat, bvec=rhs, Qmat=objQ, lb=lb, ub=ub, + sense=dir, control=list(trace=0)) + +# Solve optimization with PortfolioAnalytics +opt.pa <- optimize.portfolio(R, portf, optimize_method="cplex") +weights <- as.numeric(extractWeights(opt.pa)) + +test_that("Box with Shorting: PortfolioAnalytics and Rcplex solution weights are equal", { + expect_that(weights, equals(opt.rcplex$xopt)) +}) + +test_that("Box with Shorting: PortfolioAnalytics bounds are respected", { + expect_that(all(weights >= lb) & all(weights <= ub), is_true()) +}) + +test_that("Box with Shorting: Rcplex bounds are respected", { + expect_that(all(opt.rcplex$xopt >= lb) & all(opt.rcplex$xopt <= ub), is_true()) +}) + +test_that("Box with Shorting: PortfolioAnalytics and Rcplex solution objective values are equal", { + expect_that(opt.pa$out, equals(opt.rcplex$obj)) +}) + +Rcplex.close() + [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3606 From noreply at r-forge.r-project.org Wed Mar 4 15:10:08 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 4 Mar 2015 15:10:08 +0100 (CET) Subject: [Returnanalytics-commits] r3607 - pkg/PerformanceAnalytics/sandbox Message-ID: <20150304141008.8F991185A2D@r-forge.r-project.org> Author: peter_carl Date: 2015-03-04 15:10:08 +0100 (Wed, 04 Mar 2015) New Revision: 3607 Added: pkg/PerformanceAnalytics/sandbox/table.RiskStats.R Log: - from symposium 2013 Added: pkg/PerformanceAnalytics/sandbox/table.RiskStats.R =================================================================== --- pkg/PerformanceAnalytics/sandbox/table.RiskStats.R (rev 0) +++ pkg/PerformanceAnalytics/sandbox/table.RiskStats.R 2015-03-04 14:10:08 UTC (rev 3607) @@ -0,0 +1,229 @@ +# Additional and re-organized tables for WB presentations + +table.RiskStats <- +function (R, ci = 0.95, scale = NA, Rf = 0, MAR = .1/12, p= 0.95, digits = 4) +{# @author Peter Carl + # Risk Statistics: Statistics and Stylized Facts + + y = checkData(R, method = "zoo") + if(!is.null(dim(Rf))) + Rf = checkData(Rf, method = "zoo") + # Set up dimensions and labels + columns = ncol(y) + rows = nrow(y) + columnnames = colnames(y) + rownames = rownames(y) + + if(is.na(scale)) { + freq = periodicity(y) + switch(freq$scale, + minute = {stop("Data periodicity too high")}, + hourly = {stop("Data periodicity too high")}, + daily = {scale = 252}, + weekly = {scale = 52}, + monthly = {scale = 12}, + quarterly = {scale = 4}, + yearly = {scale = 1} + ) + } + + # for each column, do the following: + for(column in 1:columns) { + x = na.omit(y[,column,drop=FALSE]) + # for each column, make sure that R and Rf are for the same dates + if(!is.null(dim(Rf))){ # if Rf is a column + z = merge(x,Rf) + zz = na.omit(z) + x = zz[,1,drop=FALSE] + Rf.subset = zz[,2,drop=FALSE] + } + else { # unless Rf is a single number + Rf.subset = Rf + } + + z = c( + Return.annualized(x, scale = scale), + StdDev.annualized(x, scale = scale), + SharpeRatio.annualized(x, scale = scale, Rf = Rf), + DownsideDeviation(x,MAR=0)*sqrt(scale),# Add annualization to this function + SortinoRatio(x)*sqrt(scale), # New function adds annualization + PerformanceAnalytics:::AverageDrawdown(x), + maxDrawdown(x), + SterlingRatio(x), + VaR(x, p=p,method="historical"), + ES(x, p=p,method="historical"), + skewness(x), + kurtosis(x), + VaR(x, p=p), + ES(x, p=p), + SharpeRatio(x, p=p, Rf=Rf, FUN="ES", annualize=TRUE), + length(x) + ) + znames = c( + "Annualized Return", + "Annualized Std Dev", + "Annualized Sharpe Ratio", + "Annualized Downside Deviation", + "Annualized Sortino Ratio", + "Average Drawdown", + "Maximum Drawdown", + "Sterling Ratio (10%)", + paste("Historical VaR (",base::round(p*100,1),"%)",sep=""), + paste("Historical ETL (",base::round(p*100,1),"%)",sep=""), + "Skewness", + "Excess Kurtosis", + paste("Modified VaR (",base::round(p*100,1),"%)",sep=""), + paste("Modified ETL (",base::round(p*100,1),"%)",sep=""), + paste("Annualized Modified Sharpe Ratio (ETL ", base::round(p*100,1),"%)",sep=""), + "# Obs" + ) + if(column == 1) { + resultingtable = data.frame(Value = z, row.names = znames) + } + else { + nextcolumn = data.frame(Value = z, row.names = znames) + resultingtable = cbind(resultingtable, nextcolumn) + } + } + colnames(resultingtable) = columnnames + ans = base::round(resultingtable, digits) + ans +} + +table.PerfStats <- +function (R, scale = NA, Rf = 0, digits = 4) +{# @author Peter Carl + # Performance Statistics: Statistics and Stylized Facts + + y = checkData(R) + if(!is.null(dim(Rf))) + Rf = checkData(Rf) + # Set up dimensions and labels + columns = ncol(y) + rows = nrow(y) + columnnames = colnames(y) + rownames = rownames(y) + + if(is.na(scale)) { + freq = periodicity(y) + switch(freq$scale, + minute = {stop("Data periodicity too high")}, + hourly = {stop("Data periodicity too high")}, + daily = {scale = 252}, + weekly = {scale = 52}, + monthly = {scale = 12}, + quarterly = {scale = 4}, + yearly = {scale = 1} + ) + } + + # for each column, do the following: + for(column in 1:columns) { + x = na.omit(y[,column,drop=FALSE]) + # for each column, make sure that R and Rf are for the same dates + if(!is.null(dim(Rf))){ # if Rf is a column + z = merge(x,Rf) + zz = na.omit(z) + x = zz[,1,drop=FALSE] + Rf.subset = zz[,2,drop=FALSE] + } + else { # unless Rf is a single number + Rf.subset = Rf + } + + z = c( + Return.cumulative(x), + Return.annualized(x, scale = scale), + StdDev.annualized(x, scale = scale), + length(subset(x, x>0)), + length(subset(x, x<=0)), + length(subset(x, x>0))/length(x), + mean(subset(x, x>0)), + mean(subset(x, x<=0)), + mean(x), + AverageDrawdown(x), + AverageRecovery(x) + ) + znames = c( + "Cumulative Return", + "Annualized Return", + "Annualized Std Dev", + "# Positive Months", + "# Negative Months", + "% Positive Months", + "Average Positive Month", + "Average Negative Month", + "Average Month", + "Average Drawdown", + "Average Months to Recovery" + ) + if(column == 1) { + resultingtable = data.frame(Value = z, row.names = znames) + } + else { + nextcolumn = data.frame(Value = z, row.names = znames) + resultingtable = cbind(resultingtable, nextcolumn) + } + } + colnames(resultingtable) = columnnames + ans = base::round(resultingtable, digits) + ans +} + +table.RiskContribution <- function(R, p, ..., weights=NULL, scale=NA, geometric = TRUE) { + + R = na.omit(R) + if(is.null(weights)) { + message("no weights passed in, assuming equal weighted portfolio") + weights = rep(1/dim(R)[[2]], dim(R)[[2]]) + } + if (is.na(scale)) { + freq = periodicity(R) + switch(freq$scale, minute = { + stop("Data periodicity too high") + }, hourly = { + stop("Data periodicity too high") + }, daily = { + scale = 252 + }, weekly = { + scale = 52 + }, monthly = { + scale = 12 + }, quarterly = { + scale = 4 + }, yearly = { + scale = 1 + }) + } + + # Returns + # ret.col = colMeans(R)*weights + ret.col = Return.annualized(R, geometric=geometric)*weights + percret.col = ret.col/sum(ret.col) + result = cbind(t(ret.col), t(percret.col)) + # Standard Deviation + sd.cols = StdDev(R, weights=weights, invert=TRUE, portfolio_method="component", p=(1-1/12)) + result = cbind(sd.cols$contribution*sqrt(scale), sd.cols$pct_contrib_StdDev, result) + # VaR? + var.cols = VaR(R, weights=weights, method="gaussian", portfolio_method="component", p=(1-1/12)) + result = cbind(var.cols$contribution, var.cols$pct_contrib_VaR, result) + + mvar.cols = VaR(R, weights=weights, method="gaussian", portfolio_method="component", p=(1-1/12)) + result = cbind(mvar.cols$contribution, mvar.cols$pct_contrib_VaR, result) + + # ES + es.cols = ES(R, weights=weights, method="gaussian", portfolio_method="component", p=(1-1/12)) + result = cbind(es.cols$contribution, es.cols$pct_contrib_ES, result) + + mes.cols = ES(R, weights=weights, method="modified", portfolio_method="component", p=(1-1/12)) + result = cbind(weights, mes.cols$contribution, mes.cols$pct_contrib_MES, result) + total = colSums(result) + + result = rbind(result, colSums(result)) + rownames(result) = c(colnames(R),"Total") +# colnames(result) = c("Weights", "Contribution to mETL", "Percentage Contribution to mETL", "Contribution to gETL", "Percentage Contribution to gETL", "Contribution to Annualized StdDev", "Percentage Contribution to StdDev", "Contribution to Annualized E(R)", "Percentage Contribution to E(R)") + + colnames(result) = c("Weights", "Contribution to mETL", "%Contribution to mETL", "Contribution to gETL", "%Contribution to gETL", "Contribution to mVaR", "%Contribution to mVaR", "Contribution to gVaR", "%Contribution to gVaR", "Contribution to Annualized StdDev", "%Contribution to StdDev", "Contribution to Annualized E(R)", "%Contribution to E(R)") + return(result) + +} From noreply at r-forge.r-project.org Wed Mar 4 19:47:02 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 4 Mar 2015 19:47:02 +0100 (CET) Subject: [Returnanalytics-commits] r3608 - in pkg/FactorAnalytics: sandbox tests Message-ID: <20150304184702.35AB6186F3F@r-forge.r-project.org> Author: chenyian Date: 2015-03-04 19:47:01 +0100 (Wed, 04 Mar 2015) New Revision: 3608 Added: pkg/FactorAnalytics/tests/factorAnalytics.pdf Removed: pkg/FactorAnalytics/sandbox/Man/ Log: Add a reference manual in the test folder. Added: pkg/FactorAnalytics/tests/factorAnalytics.pdf =================================================================== --- pkg/FactorAnalytics/tests/factorAnalytics.pdf (rev 0) +++ pkg/FactorAnalytics/tests/factorAnalytics.pdf 2015-03-04 18:47:01 UTC (rev 3608) @@ -0,0 +1,9944 @@ +%PDF-1.5 +%???? +1 0 obj +<< /S /GoTo /D (Rfn.CommonFactors.1) >> +endobj +4 0 obj +(CommonFactors) +endobj +5 0 obj +<< /S /GoTo /D (Rfn.dCornishFisher.1) >> +endobj +8 0 obj +(dCornishFisher) +endobj +9 0 obj +<< /S /GoTo /D (Rfn.fitSfm.1) >> +endobj +12 0 obj +(fitSfm) +endobj +13 0 obj +<< /S /GoTo /D (Rfn.fitTsfm.1) >> +endobj +16 0 obj +(fitTsfm) +endobj +17 0 obj +<< /S /GoTo /D (Rfn.fitTsfm.control.1) >> +endobj +20 0 obj +(fitTsfm.control) +endobj +21 0 obj +<< /S /GoTo /D (Rfn.fitTsfmLagBeta.1) >> +endobj +24 0 obj +(fitTsfmLagBeta) +endobj +25 0 obj +<< /S /GoTo /D (Rfn.fitTsfmMT.1) >> +endobj +28 0 obj +(fitTsfmMT) +endobj +29 0 obj +<< /S /GoTo /D (Rfn.fitTsfmUpDn.1) >> +endobj +32 0 obj +(fitTsfmUpDn) +endobj +33 0 obj +<< /S /GoTo /D (Rfn.fmCov.1) >> +endobj +36 0 obj +(fmCov) +endobj +37 0 obj +<< /S /GoTo /D (Rfn.fmEsDecomp.1) >> +endobj +40 0 obj +(fmEsDecomp) +endobj +41 0 obj +<< /S /GoTo /D (Rfn.fmSdDecomp.1) >> +endobj +44 0 obj +(fmSdDecomp) +endobj +45 0 obj +<< /S /GoTo /D (Rfn.fmVaRDecomp.1) >> +endobj +48 0 obj +(fmVaRDecomp) +endobj +49 0 obj +<< /S /GoTo /D (Rfn.managers.1) >> +endobj +52 0 obj +(managers) +endobj +53 0 obj +<< /S /GoTo /D (Rfn.paFm.1) >> +endobj +56 0 obj +(paFm) +endobj +57 0 obj +<< /S /GoTo /D (Rfn.plot.pafm.1) >> +endobj +60 0 obj +(plot.pafm) +endobj +61 0 obj +<< /S /GoTo /D (Rfn.plot.sfm.1) >> +endobj +64 0 obj +(plot.sfm) +endobj +65 0 obj +<< /S /GoTo /D (Rfn.plot.tsfm.1) >> +endobj +68 0 obj +(plot.tsfm) +endobj +69 0 obj +<< /S /GoTo /D (Rfn.plot.tsfmUpDn.1) >> +endobj +72 0 obj +(plot.tsfmUpDn) +endobj +73 0 obj +<< /S /GoTo /D (Rfn.predict.sfm.1) >> +endobj +76 0 obj +(predict.sfm) +endobj +77 0 obj +<< /S /GoTo /D (Rfn.predict.tsfm.1) >> +endobj +80 0 obj +(predict.tsfm) +endobj +81 0 obj +<< /S /GoTo /D (Rfn.predict.tsfmUpDn.1) >> +endobj +84 0 obj +(predict.tsfmUpDn) +endobj +85 0 obj +<< /S /GoTo /D (Rfn.print.pafm.1) >> +endobj +88 0 obj +(print.pafm) +endobj +89 0 obj +<< /S /GoTo /D (Rfn.print.sfm.1) >> +endobj +92 0 obj +(print.sfm) +endobj +93 0 obj +<< /S /GoTo /D (Rfn.print.tsfm.1) >> +endobj +96 0 obj +(print.tsfm) +endobj +97 0 obj +<< /S /GoTo /D (Rfn.print.tsfmUpDn.1) >> +endobj +100 0 obj +(print.tsfmUpDn) +endobj +101 0 obj +<< /S /GoTo /D (Rfn.Stock.df.1) >> +endobj +104 0 obj +(Stock.df) +endobj +105 0 obj +<< /S /GoTo /D (Rfn.StockReturns.1) >> +endobj +108 0 obj +(StockReturns) +endobj +109 0 obj +<< /S /GoTo /D (Rfn.summary.pafm.1) >> +endobj +112 0 obj +(summary.pafm) +endobj +113 0 obj +<< /S /GoTo /D (Rfn.summary.sfm.1) >> +endobj +116 0 obj +(summary.sfm) +endobj +117 0 obj +<< /S /GoTo /D (Rfn.summary.tsfm.1) >> +endobj +120 0 obj +(summary.tsfm) +endobj +121 0 obj +<< /S /GoTo /D (Rfn.summary.tsfmUpDn.1) >> +endobj +124 0 obj +(summary.tsfmUpDn) +endobj +125 0 obj +<< /S /GoTo /D (Rfn.TreasuryYields.1) >> +endobj +128 0 obj +(TreasuryYields) +endobj +129 0 obj +<< /S /GoTo /D (index.0) >> +endobj +132 0 obj +(Index) +endobj +133 0 obj +<< /S /GoTo /D [134 0 R /Fit] >> +endobj +146 0 obj << +/Length 1348 +/Filter /FlateDecode +>> +stream +x??Xmo?6??_?o??!??b??vi?! +?????J??V?4?N???EJ?TGn????????{??;???'? ??|???-???? ?(?h8Y?&$?(????(???2??????7nw??_??C??O$?????kxh?0?:??????3??> endobj +135 0 obj << +/Type /Annot +/Border[0 0 0]/H/I/C[0 1 1] +/Rect [125.362 225.622 347.529 236.213] +/Subtype/Link/A<> +>> endobj +136 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [506.111 171.53 513.085 180.277] +/A << /S /GoTo /D (page.2) >> +>> endobj +137 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [506.111 159.476 513.085 168.322] +/A << /S /GoTo /D (page.3) >> +>> endobj +138 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [506.111 147.62 513.085 156.367] +/A << /S /GoTo /D (page.4) >> +>> endobj +139 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [506.111 135.565 513.085 144.143] +/A << /S /GoTo /D (page.7) >> +>> endobj +140 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 123.71 513.085 132.457] +/A << /S /GoTo /D (page.11) >> +>> endobj +141 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 111.655 513.085 120.502] +/A << /S /GoTo /D (page.13) >> +>> endobj +147 0 obj << +/D [134 0 R /XYZ 99.346 773.487 null] +>> endobj +148 0 obj << +/D [134 0 R /XYZ 100.346 742.532 null] +>> endobj +149 0 obj << +/D [134 0 R /XYZ 100.346 742.532 null] +>> endobj +153 0 obj << +/D [134 0 R /XYZ 100.346 212.726 null] +>> endobj +145 0 obj << +/Font << /F35 150 0 R /F36 151 0 R /F22 152 0 R /F39 154 0 R >> +/ProcSet [ /PDF /Text ] +>> endobj +188 0 obj << +/Length 1480 +/Filter /FlateDecode +>> +stream +x??Z?v?H??+X???(?,mI?r??????8YT??MG?R?t??]? ?id+? +S????o@~?????jt?^L?oE ??o?k A??[?%??????????????/?r=????"?:??lU?TSF???`?????\(?Y?3????u6?Sj?????????6?P?? ??z5????u?????k?????(=???v?;n????sP?~??oP_g?????r ??"m`??????U?m7??< r??e?@?{????'?????-n??????z!???]s???H???????M3??0??E? ??l7E?l-???????R??{??????k??j ?? ~r5x???|????p?????'??v?&?O}?/????j??|e???(??9??????????H?&??p??????P?Il???????!??P?H?O?h??Ix?^???*V_A???-Z?--,x?y9????????-wY????eNo2?( ???8=qb?!?????????C?Y?O??4????'??~??Bm?Y??O?v?7?????$~?? ??)??z??4?\,u???Y????w? A??????$}!=?????k????@+??o?r$ +?????$9Zk9????a?r?v?????E??w??,??hg6Q???L??.?S?x?.ye????%.t???Wz?????J???????4}????}?pp 8?|?>P?HHhT{?1/W"?Vi????N ?$ +?6n6|?'w0??/??V???~?UT7?%?V7 +4,????c????Wi?|E???Rg.? ??b|H?+Y??_??`d???fM)?=??(???+?LWj?a^??????R?I^O??(?[????Q?;??%??B????X???qw???????O ??? ?b?|[(?Z?W7???_???a??VE^V,?L???ie?????K$)?.&??@??h???s4.?c0kP??d?`I??Nm?^?T?]?%0???$?-?p?9??1???<_)?w?> endobj +142 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 731.474 513.085 740.321] +/A << /S /GoTo /D (page.16) >> +>> endobj +143 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 719.399 513.085 728.365] +/A << /S /GoTo /D (page.19) >> +>> endobj +144 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 707.663 513.085 716.41] +/A << /S /GoTo /D (page.21) >> +>> endobj +162 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 695.608 513.085 704.455] +/A << /S /GoTo /D (page.23) >> +>> endobj +163 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 683.653 513.085 692.5] +/A << /S /GoTo /D (page.25) >> +>> endobj +164 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 671.698 513.085 680.545] +/A << /S /GoTo /D (page.27) >> +>> endobj +165 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 659.623 513.085 668.59] +/A << /S /GoTo /D (page.29) >> +>> endobj +166 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 647.788 513.085 656.634] +/A << /S /GoTo /D (page.30) >> +>> endobj +167 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 635.833 513.085 644.679] +/A << /S /GoTo /D (page.31) >> +>> endobj +168 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 623.877 513.085 632.724] +/A << /S /GoTo /D (page.32) >> +>> endobj +169 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 611.922 513.085 620.769] +/A << /S /GoTo /D (page.34) >> +>> endobj +170 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 599.967 513.085 608.814] +/A << /S /GoTo /D (page.37) >> +>> endobj +171 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 588.012 513.085 596.859] +/A << /S /GoTo /D (page.38) >> +>> endobj +172 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 575.937 513.085 584.903] +/A << /S /GoTo /D (page.39) >> +>> endobj +173 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 564.102 513.085 572.948] +/A << /S /GoTo /D (page.40) >> +>> endobj +174 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 552.246 513.085 560.993] +/A << /S /GoTo /D (page.41) >> +>> endobj +175 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 540.291 513.085 549.038] +/A << /S /GoTo /D (page.41) >> +>> endobj +176 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 528.336 513.085 537.083] +/A << /S /GoTo /D (page.42) >> +>> endobj +177 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 516.281 513.085 525.128] +/A << /S /GoTo /D (page.43) >> +>> endobj +178 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 504.326 513.085 513.172] +/A << /S /GoTo /D (page.43) >> +>> endobj +179 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 492.47 513.085 501.217] +/A << /S /GoTo /D (page.44) >> +>> endobj +180 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 480.415 513.085 489.262] +/A << /S /GoTo /D (page.45) >> +>> endobj +181 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 468.46 513.085 477.307] +/A << /S /GoTo /D (page.45) >> +>> endobj +182 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 456.505 513.085 465.352] +/A << /S /GoTo /D (page.47) >> +>> endobj +183 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 444.55 513.085 453.397] +/A << /S /GoTo /D (page.48) >> +>> endobj +184 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 432.475 513.085 441.441] +/A << /S /GoTo /D (page.49) >> +>> endobj +185 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [501.13 410.657 513.085 419.633] +/A << /S /GoTo /D (page.51) >> +>> endobj +156 0 obj << +/D [187 0 R /XYZ 99.346 773.487 null] +>> endobj +190 0 obj << +/D [187 0 R /XYZ 100.346 395.442 null] +>> endobj +2 0 obj << +/D [187 0 R /XYZ 100.346 395.442 null] +>> endobj +192 0 obj << +/D [187 0 R /XYZ 100.346 359.649 null] +>> endobj +193 0 obj << +/D [187 0 R /XYZ 100.346 359.649 null] +>> endobj +194 0 obj << +/D [187 0 R /XYZ 100.346 350.55 null] +>> endobj +195 0 obj << +/D [187 0 R /XYZ 100.346 145.119 null] +>> endobj +186 0 obj << +/Font << /F36 151 0 R /F44 189 0 R /F35 150 0 R /F22 152 0 R /F45 191 0 R >> +/ProcSet [ /PDF /Text ] +>> endobj +224 0 obj << +/Length 1451 +/Filter /FlateDecode +>> +stream +x??WK??6 ??W?(wV4I?z???????$?&?:?LG?h[?%?z?n?? >dK??Y???A???????????&?cV?B?z???"#?y??a?]j?%????)??TWS?rl?i&??e*?j??G???&J;?0? ?O??U?EY??C?z>?( ?u?m????7vl??Yo??}?????? p?6?p??n??/7?9g??F ???n?!???S??S????c\???? ?????w8??B$????????0%?6???????X??Q?????????+???[%h7??'??y ???w?f?n??x??z[4i? *??lU???^??N???s.?5????MQhgi?????E!?7VZ +?.5???????M???Cu? @!??8???V?o?^7 ?G%?Y??3?[????? P?G?`?1bq??0?QHT?{?)#??????2n?? +=1??~?Ey???7?)??/qT9?+??. ??k.??Lwu{?e?5`w?}?q?f??,?????t)?j?R????j?X??????:?B??.>lj?(O???Q???Z?PfF?4U????X???s?3?!x?kkwe??fJ +#?\?<>W??y?8C???I#?? ????????x4C??)kI ????????????????u??E?:??(k??H????????w?Eg?c??W vl??L??n>?????MM????{?????V????f??y?kH??L??Kr?M? +=?b?=??_nOG????d??7?R s?a?A?f??*?>?%?6???y?k???:Gt?R??*?v?Z??V??z????ND?/8?w???)7?UU?]???e?K?3u+??e?????\TW?N???? ?\O1???RUQ?WX??? +l????6??krX???8?k?d???Cz?????se2??@OO ??\?d?D?????&?>??o7h?JZ???^=??vn?I??@????\?Q???x?????P??P?????T?]???\??????(X'k??L?U?E? {@? vp??_????]?vM-IJ^q?????i=$?@ |?U?a?U???????Y!'?]??,?&k]?j???&?u?-?:?NU?J??T&"???n?J?^??Z?*t?G?u/7T???0-?`??1?v??ZS?G??/???/?FoHat?TN4? 9) !??>?*?!A???kPf??E9 NPV?(??F9 ?(?a?]?R?/????/H^#??GD??.a??^??nb?9?Z?a???h???,?? ??4?b???!????k??Rb??H?j??G?-?Sb?.?????? ????q??8??b???e??:?J?eT c??Or?]???(b??}@+_??r?@???f???F/k :???B??; +endstream +endobj +223 0 obj << +/Type /Page +/Contents 224 0 R +/Resources 222 0 R +/MediaBox [0 0 595.276 841.89] +/Parent 155 0 R +/Annots [ 220 0 R 221 0 R ] +>> endobj +220 0 obj << +/Type /Annot +/Border[0 0 0]/H/I/C[0 1 1] +/Rect [307.615 630.547 493.916 641.078] +/Subtype/Link/A<> +>> endobj +221 0 obj << +/Type /Annot +/Border[0 0 0]/H/I/C[0 1 1] +/Rect [204.722 614.864 331.247 625.345] +/Subtype/Link/A<> +>> endobj +157 0 obj << +/D [223 0 R /XYZ 99.346 773.487 null] +>> endobj +225 0 obj << +/D [223 0 R /XYZ 100.346 744.525 null] +>> endobj +226 0 obj << +/D [223 0 R /XYZ 100.346 663.962 null] +>> endobj +227 0 obj << +/D [223 0 R /XYZ 100.346 589.105 null] +>> endobj +6 0 obj << +/D [223 0 R /XYZ 100.346 589.105 null] +>> endobj +228 0 obj << +/D [223 0 R /XYZ 100.346 552.035 null] +>> endobj +229 0 obj << +/D [223 0 R /XYZ 100.346 552.035 null] +>> endobj +230 0 obj << +/D [223 0 R /XYZ 100.346 552.035 null] +>> endobj +231 0 obj << +/D [223 0 R /XYZ 100.346 552.035 null] +>> endobj +232 0 obj << +/D [223 0 R /XYZ 100.346 542.649 null] +>> endobj +233 0 obj << +/D [223 0 R /XYZ 100.346 485.582 null] +>> endobj +234 0 obj << +/D [223 0 R /XYZ 100.346 368.739 null] +>> endobj +235 0 obj << +/D [223 0 R /XYZ 100.346 217.274 null] +>> endobj +222 0 obj << +/Font << /F44 189 0 R /F36 151 0 R /F35 150 0 R /F22 152 0 R /F45 191 0 R >> +/ProcSet [ /PDF /Text ] +>> endobj +238 0 obj << +/Length 1625 +/Filter /FlateDecode +>> +stream +x??WYs?6~???8?& +???N??:vf:n?Fr;m??P$d?T,??w,)2?b?A"?=????Xw?????B??:W'???A?d??L?T-??G1?????H?,(??Y7r???f??(??\?? ?e?????`*y?G4?????fr4qcb?f+$?Ga`? +???0v????^$?}?X.k?W#J?}??????E?fC???ub??i??.??.b?a ?D?I +v????gG]?4)?A??????gDJ??A?`"?A???}??-?b???O[oP???????m?T???????C??;?e> +?MlJ??D??{".?i?q9? +?+?S??_?h???>?P???'??L/7??Tq?*?????nd?"5N????M??}U'p?^??s??k+?)!?2??????1???V?x???R\??g?<6??'1?8??????hf>AOj??c??W????.??D_?&??,h???????`X?!w?????n??Lx???)?x???Vw??? ?:y?ro?H???%?%:??f9(? ??K???=???B???????'?c??GK????????E= ??????*2??[8???jy?;S8?Xn ?=x2???g??+?M`?xqd=????? 4?2?Z???Nu???? L2y?"q??k>???GF?8j???? >?c?UC8??R?q^f ???wf/r???!P?C?zX???????h;>???S??z +???#o?L???z)??????~?#???[?D?Z????????? ?}?b?F??jM? ??Y&{?a?r???]??V??`?~?????E?z??W5?7q?X;u?zU???HI?,?????V???"/?U??n???>??S?M?&???:??6T?:m??F?u???????h?D??=??tTA???p6[mG?xs? ?mW??h???>??9??SK?+??????????eoer?^dO??)u?R?D7"?$???? +%??????7[????/??^5???m?:*??~4???? ?D@%??M?q??YS?????p??DN%?5????!?^%LZ???? ????\??????= +endstream +endobj +237 0 obj << +/Type /Page +/Contents 238 0 R +/Resources 236 0 R +/MediaBox [0 0 595.276 841.89] +/Parent 155 0 R +>> endobj +158 0 obj << +/D [237 0 R /XYZ 99.346 773.487 null] +>> endobj +239 0 obj << +/D [237 0 R /XYZ 100.346 744.525 null] +>> endobj +240 0 obj << +/D [237 0 R /XYZ 100.346 687.446 null] +>> endobj +241 0 obj << +/D [237 0 R /XYZ 100.346 642.322 null] +>> endobj +242 0 obj << +/D [237 0 R /XYZ 100.346 585.242 null] +>> endobj +243 0 obj << +/D [237 0 R /XYZ 100.346 318.717 null] +>> endobj +10 0 obj << +/D [237 0 R /XYZ 100.346 318.717 null] +>> endobj +244 0 obj << +/D [237 0 R /XYZ 100.346 281.594 null] +>> endobj +245 0 obj << +/D [237 0 R /XYZ 100.346 281.594 null] +>> endobj +246 0 obj << +/D [237 0 R /XYZ 100.346 281.594 null] +>> endobj +247 0 obj << +/D [237 0 R /XYZ 100.346 272.196 null] +>> endobj +248 0 obj << +/D [237 0 R /XYZ 100.346 191.206 null] +>> endobj +236 0 obj << +/Font << /F36 151 0 R /F44 189 0 R /F35 150 0 R /F22 152 0 R /F45 191 0 R >> +/ProcSet [ /PDF /Text ] +>> endobj +253 0 obj << +/Length 2705 +/Filter /FlateDecode +>> +stream +x??YYo?F~????O?????y??8????v??G????^????????? +?2????yb???f?'?O?K;S?k? +B???A???s]?@9$"??nG#?fb??CS???B:?Z/?8?]j +X??}??V2~????EQ??F?#?????x??IQD???????l??o???\J????dm +?????2? +?t;M?z?????????\???{N???M?????UP???W????"m@?~?d|M??)%???c|%~G? BW?w?'dun?????O ?.?=xQ?#?-??:?D$Q B?u??????Y??????w_5?I^FR^0}????????o ??*?q +)?L]??????T?@X??,?????? a>&????,4??s?-?z????yI??? 9?D?? +_??2(?,?2M4?uE#?0%C?@*????????s](???x?Bzt?~??f;??~????Z??/B.?1)?P0G??????? xj??Y?6?n>?D???U?U.?E???????7?Kv??????????du?|??7>??r? +Cr5P {?.?h?Tm???~X???;???(e[c???>??kx ?b?6????q0?7????WLV?{?8?Y?J%2V???T??Ot???~?????u??,@?@FoGK?????O???????M*??CH*??x???????? +2?:??)=?"????????Z?c!?A??b? c????v&?M??^????=*R??O??S{?/b????????????????B U?{z?=?[_?????? r????u? ~P?P|?@????~?E?x?? ?Y???U?[??????/)K +?+N>??%?OL?9-F?????P`??.??? ?(??s?1?o?|??? ?? +?jx?P??\?4!?j???"^w6?7?????{????*??]?h?{f??3?(??????!$???o??p&Xx?????????????PV-y?>?i)?p??H???#???v?3 ??K?N??Z?Kr?mV??>?3B +YK"!?ySk?}T???y???Z?P???Pp? ?4?8{?@?(-? +??? +???imb?U{,?] +C=x?Bwb???e?j????g??????W6?(?R1???;m0~??????sO???QC??B??L??P???>?M??&f(G?[?d????D?u?j?? %a?s???L???'?M]?h0B? ???{?Z?????k[ah@???????#?` n$Q???31?e??@??3A?????h*??}???j^????R???=c???G-??;??G???????0q?@hq???J'R???js\??w?Z??Y[???S*?b????\@????l????C??????]?u{$5*?G.??`??e>pj??W??p?$H???????O(?????DH[??7?u?? +??)?????\n*?? ?sgy?u?4:mIa}??????h*D????iw????g?:"??????&?.o???[H?1 M???r C#?O?Z)??????d???p?????C?ol\m_??}???l??aOy?? +n?D???oN???Pn>?????p?????????iP??"?qq?k?g +?_c?? I??y!-??z>/???xZ?????imVU??qsi?????? /??a?k?? '?!`[ +??hE??%????Fc?C +?? +]????'n? + Vcd?8?)???C?????`lY?}???O??FP? +endstream +endobj +252 0 obj << +/Type /Page +/Contents 253 0 R +/Resources 251 0 R +/MediaBox [0 0 595.276 841.89] +/Parent 155 0 R +/Annots [ 249 0 R 250 0 R ] +>> endobj +249 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [312.587 436.3 324.542 447.204] +/A << /S /GoTo /D (Rfn.lm) >> +>> endobj +250 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [347.621 361.081 384.482 371.985] +/A << /S /GoTo /D (Rfn.na.omit) >> +>> endobj +254 0 obj << +/D [252 0 R /XYZ 99.346 773.487 null] +>> endobj +255 0 obj << +/D [252 0 R /XYZ 100.346 656.984 null] +>> endobj +256 0 obj << +/D [252 0 R /XYZ 100.346 407.253 null] +>> endobj +251 0 obj << +/Font << /F44 189 0 R /F36 151 0 R /F22 152 0 R /F35 150 0 R >> +/ProcSet [ /PDF /Text ] +>> endobj +273 0 obj << +/Length 2083 +/Filter /FlateDecode +>> +stream +x??YY??6~??P?C?????Og?*;??FZ?v7??? 1??|??o7?$jF?L??>?>?l????????????x?$aI(??b=?????7???0<?@b?????j?^????a0 +O2?3?:{]|??lu??v??d??lf?,P?F;?/?~&?R???L?8??S??M +x?AV`#R'??aT?&?(?C4?S?????S?:Y?R?????t?I>f???T??|p'?d???cO??hJR???k?s?ohMZ?d]?i?8~i?!?E????? }??q???O`?0????`? ??0????Br1?+jc?;?p??????? +??,=?2)?j$?\?w(???#???,2?????????$d?????9=)Mdn ?*m?U?b??|?\`1p??a?i?#? +?I +??:b???E??,?????????*??????}VX?C???????U??????7?O7??7???????I???[??4????:?'?@?R?T?-??s??i!W?(??q?Q???$E???'Aq?eeV=?p?F?????,?P +??????hSz!?????k?]X???<?T??z;{O???V?3? ?W?V???~V???e#]?P1_#??Z???M?B???2G??&?????a1(?? ??gv?????}????n???????????(??u?xk?????hS?v????`???@???????*????k???>Y??J;????o????3rkKI +?)?? +??v??????bVC?r?g:?o?+????????=?|>????(k(?tA?/???.7? +???o? +$^n??o??????a\?Z?T0???????v]?]so?j9???^:/?t?Yl??A"Cu????W???U??|\??U?F???????b???o????,. S<@NA?]/??'l?7???v +????,1?T&?\?{??????6??>???2??FAkl^?G?S i%???= +G?????[J??+r??????B???FyC?y???????~c?sF??7D?Qg?g[??P?C?=CE?Pq????s: w???jn???t??E?ez?Y???K?l?Hk??E?9?kwx???k?????s`W???/?N?$???T?.????>?Gh?????a?????*? ??&a=??????.???Sz3.?O?!;?l???|G???S????e4???I??R?W???h?Y]?M??]o???????w??NAr?h????q?c?{????LoseY??UqEv[Pg????t-????8$1????f/????+m??X<)QL??\??~??U?? :? ?? +??8??j??????,J??3??????yB4???0dq?> endobj +259 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [277.877 154.384 319.72 165.288] +/A << /S /GoTo /D (Rfn.plot.sfm) >> +>> endobj +260 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [322.709 154.384 379.496 165.288] +/A << /S /GoTo /D (Rfn.predict.sfm) >> +>> endobj +261 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [382.484 154.384 429.309 165.288] +/A << /S /GoTo /D (Rfn.print.sfm) >> +>> endobj +262 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [446.684 154.384 503.471 165.288] +/A << /S /GoTo /D (Rfn.summary.sfm) >> +>> endobj +263 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [273.254 138.805 295.172 149.709] +/A << /S /GoTo /D (Rfn.coef) >> +>> endobj +264 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [297.683 138.805 329.563 149.709] +/A << /S /GoTo /D (Rfn.fitted) >> +>> endobj +265 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [332.074 138.805 378.898 149.709] +/A << /S /GoTo /D (Rfn.residuals) >> +>> endobj +266 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [381.409 138.805 408.308 149.709] +/A << /S /GoTo /D (Rfn.fmCov) >> +>> endobj +267 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [410.818 138.805 462.624 149.709] +/A << /S /GoTo /D (Rfn.fmSdDecomp) >> +>> endobj +268 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [465.135 138.805 521.922 149.709] +/A << /S /GoTo /D (Rfn.fmVaRDecomp) >> +>> endobj +269 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [134.227 127.333 186.033 137.754] +/A << /S /GoTo /D (Rfn.fmEsDecomp) >> +>> endobj +270 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [117.35 111.754 139.268 122.175] +/A << /S /GoTo /D (Rfn.paFm) >> +>> endobj +274 0 obj << +/D [272 0 R /XYZ 99.346 773.487 null] +>> endobj +275 0 obj << +/D [272 0 R /XYZ 100.346 744.525 null] +>> endobj +276 0 obj << +/D [272 0 R /XYZ 100.346 360.533 null] +>> endobj +277 0 obj << +/D [272 0 R /XYZ 100.346 315.653 null] +>> endobj +278 0 obj << +/D [272 0 R /XYZ 100.346 188.172 null] +>> endobj +271 0 obj << +/Font << /F36 151 0 R /F44 189 0 R /F35 150 0 R /F22 152 0 R >> +/ProcSet [ /PDF /Text ] +>> endobj +293 0 obj << +/Length 1203 +/Filter /FlateDecode +>> +stream +x??VKs?6??Wp?L#??0 ??????qgZ?e??C?DB2#?p@?J?????4Y??;??o?X?????k??4?h????\ 1g?+B????X??T??T7c}?f5*????????d??|?[?~ +G?????mr}???g?c????< +endstream +endobj +292 0 obj << +/Type /Page +/Contents 293 0 R +/Resources 291 0 R +/MediaBox [0 0 595.276 841.89] +/Parent 301 0 R +>> endobj +159 0 obj << +/D [292 0 R /XYZ 99.346 773.487 null] +>> endobj +294 0 obj << +/D [292 0 R /XYZ 100.346 744.525 null] +>> endobj +295 0 obj << +/D [292 0 R /XYZ 100.346 378.756 null] +>> endobj +14 0 obj << +/D [292 0 R /XYZ 100.346 378.756 null] +>> endobj +296 0 obj << +/D [292 0 R /XYZ 100.346 341.452 null] +>> endobj +297 0 obj << +/D [292 0 R /XYZ 100.346 341.452 null] +>> endobj +298 0 obj << +/D [292 0 R /XYZ 100.346 341.452 null] +>> endobj +299 0 obj << +/D [292 0 R /XYZ 100.346 332.013 null] +>> endobj +300 0 obj << +/D [292 0 R /XYZ 100.346 250.982 null] +>> endobj +291 0 obj << +/Font << /F44 189 0 R /F36 151 0 R /F35 150 0 R /F22 152 0 R /F45 191 0 R >> +/ProcSet [ /PDF /Text ] +>> endobj +314 0 obj << +/Length 2645 +/Filter /FlateDecode +>> +stream +x??]s???=???{8z?B????!?\z?$????>??@????"?:?????]R ?8rn?p,??????"??????/^?U?E!?4J/??2 ????, +E???????A~????|??F?G"?q[~ ?????=n}2??o??;?Vi??eFG??r??a?I??????h?? M6Mi-M?????c-?(??0m??X6??0 ????MEg?????4??be"/B??\?0?=?u???k???u?HB&1!?u/?r???)?g?(?h????2 ?n|????]??u[???-B???-?? U*?w??7???????F?_6??G??????1?J?'?ft[{.?Q?QG?????I??S?2?? ?????6! +>?????Sd??M8???i8??? +??(rG?}? +?eGR>?z?.N??d .??4?}K?-?.??R?{Z?????qu??~?q? +?W?A)?]??????4LBG????D>??Y?GnO??V??F???????????>????8\???b?0F?????? [?y?){?? +??:?U6?c???\?(??? ??i?Lf?\?? ?????;?7c??????q$?ENmt??????hB"?p????i*?d???j?W"?R?j? ??z??^?N/?p?9????( +E?S6?)Pw?T???T?}??Ue_~????]/??/{S??'????/??a???????+W)yg??:??b??E?I?5R`?b?\?P.(d??e5?E???Q??l?H??L?H??S?@?Tv?&X??e?,^?L??????? +Y???H>?#2???p?X??????JRD?%??^?$*?5*:?T? ? ???7?M??????y<??)????? ??.?*?X???*F?????J?YX ???O???T|F????dA?5W?s?&6??}+;??ph?x&??*???|y?????? ?Y'a??!??tjk?=?t9h?Kb}e`p[?k?)?M???| +'|uQ?3????Le???????h????????%^?cg??u?7~5????S?????$???w?D?????2c??Sb???t????I?j???#?????e?T?L?f?#???e???ow.D!?k;??~?y??? ?b?????M3?xp?????]9?SV??4S'Y!O?+??t??N 2 E?????????"g??u?9H?h[?-}?kQ??@??L +I??????O?S??4??????_u>?W?h??A1c:|.Gmg6a??u-? \?j??dhk?>x????>??c?MYx??????z?mk?y?uv???|????'??????? +y??cLSo??5?3??#?h> endobj +302 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [462.025 422.65 538.737 433.554] +/A << /S /GoTo /D (Rfn.fitTsfm.control) >> +>> endobj +303 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [301.688 412.717 378.4 421.599] +/A << /S /GoTo /D (Rfn.fitTsfm.control) >> +>> endobj +304 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [277.439 394.257 354.151 405.16] +/A << /S /GoTo /D (Rfn.fitTsfm.control) >> +>> endobj +305 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [410.359 302.375 422.314 313.279] +/A << /S /GoTo /D (Rfn.lm) >> +>> endobj +306 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [263.022 278.465 289.922 289.369] +/A << /S /GoTo /D (Rfn.lmRob) >> +>> endobj +307 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [419.508 250.071 441.426 260.975] +/A << /S /GoTo /D (Rfn.step) >> +>> endobj +308 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] +/Rect [455.471 250.071 507.277 260.975] +/A << /S /GoTo /D (Rfn.step.lmRob) >> +>> endobj +309 0 obj << +/Type /Annot +/Subtype /Link +/Border[0 0 0]/H/I/C[1 0 0] [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3608 From noreply at r-forge.r-project.org Fri Mar 6 19:46:18 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 6 Mar 2015 19:46:18 +0100 (CET) Subject: [Returnanalytics-commits] r3609 - in pkg/FactorAnalytics: R man tests Message-ID: <20150306184619.0DF68186F81@r-forge.r-project.org> Author: chenyian Date: 2015-03-06 19:46:18 +0100 (Fri, 06 Mar 2015) New Revision: 3609 Modified: pkg/FactorAnalytics/R/fitTsfm.R pkg/FactorAnalytics/R/fitTsfmLagBeta.r pkg/FactorAnalytics/R/fitTsfmMT.r pkg/FactorAnalytics/R/fitTsfmUpDn.r pkg/FactorAnalytics/R/plot.tsfmUpDn.r pkg/FactorAnalytics/man/fitTsfm.Rd pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd pkg/FactorAnalytics/man/fitTsfmMT.Rd pkg/FactorAnalytics/man/fitTsfmUpDn.Rd pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd pkg/FactorAnalytics/tests/factorAnalytics.pdf Log: 1. Edit fitTsfmLagBeta.Rd, fitTsfmMT.Rd, fitTsfmUpDn.Rd. 2. Update user manual. Modified: pkg/FactorAnalytics/R/fitTsfm.R =================================================================== --- pkg/FactorAnalytics/R/fitTsfm.R 2015-03-04 18:47:01 UTC (rev 3608) +++ pkg/FactorAnalytics/R/fitTsfm.R 2015-03-06 18:46:18 UTC (rev 3609) @@ -36,17 +36,9 @@ #' \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. +#' factors to be added to any of the above methods. A wrapper function +#' \code{\link{fitTsfmMT}} is built based on this functionality. Please refer to +#' \code{fitTsfmMT} for detail. #' #' \subsection{Data Processing}{ #' Modified: pkg/FactorAnalytics/R/fitTsfmLagBeta.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmLagBeta.r 2015-03-04 18:47:01 UTC (rev 3608) +++ pkg/FactorAnalytics/R/fitTsfmLagBeta.r 2015-03-06 18:46:18 UTC (rev 3609) @@ -3,58 +3,18 @@ #' @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 +#' squares-DLS (or) robust regression like \code{fitTsfm}. 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. +#' The lagged returns model estimates lagged market Beta. Specifically, +#' \deqn{r_t = \alpha + \beta_0 MKT_t + \beta_1 MKT_t-1 + \ldots + \beta_K MKT_t-K + \epsilon_t, t=1 \ldots T} +#' where \eqn{r_t} is the asset returns, and MKT is the market factor. It is usually +#' needed for illiquid securities with stale prices. One can also report the sum of +#' the lagged Betas: +#' \deqn{\beta = \beta_0 + \beta_1 + \ldots + \beta_K } #' -#' 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. @@ -78,14 +38,11 @@ #' \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. +#' @return \code{fitTsfmLagBeta} also returns an object of class \code{"tsfm"} like +#' \code{fitTsfm}. The generic function such as \code{print}, \code{plot}, \code{predict} +#' and \code{summary} methods exist. Also, the generic accessor functions \code{coef}, +#' \code{fitted} \code{residuals} and \code{fmCov} can be applied as well. #' -#' 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 @@ -110,34 +67,13 @@ #' @author Yi-An Chen. #' #' @references -#' Christopherson, J. A., Carino, D. R., & Ferson, W. E. (2009). Portfolio -#' performance measurement and benchmarking. McGraw Hill Professional. +#' Scholes, M. and Williams, J. T. (1977). Estimating betas from non-synchronous +#' data, Journal of Financial Economics, vol. 5, 1977, pp. 309-327 #' -#' Efron, B., Hastie, T., Johnstone, I., & Tibshirani, R. (2004). Least angle -#' regression. The Annals of statistics, 32(2), 407-499. +#' @seealso +#' The original time series function \code{\link{fitTsfm}} and its generic functions +#' application. #' -#' 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) Modified: pkg/FactorAnalytics/R/fitTsfmMT.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmMT.r 2015-03-04 18:47:01 UTC (rev 3608) +++ pkg/FactorAnalytics/R/fitTsfmMT.r 2015-03-06 18:46:18 UTC (rev 3609) @@ -8,53 +8,13 @@ #' \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 +#' The 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. +#' 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. @@ -76,14 +36,11 @@ #' \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. +#' @return \code{fitTsfmMT} also returns an object of class \code{"tsfm"} like +#' \code{fitTsfm}. The generic function such as \code{print}, \code{plot}, \code{predict} +#' and \code{summary} methods exist. Also, the generic accessor functions \code{coef}, +#' \code{fitted} \code{residuals} and \code{fmCov} can be applied as well. #' -#' 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 @@ -108,34 +65,17 @@ #' @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. +#' #' Christopherson, J. A., Carino, D. R., & Ferson, W. E. (2009). Portfolio +#' performance measurement and benchmarking. McGraw Hill Professional. pp.127-133 #' -#' @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}}. +#' @seealso +#' The original time series function \code{\link{fitTsfm}} and its generic functions +#' application. #' -#' 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) Modified: pkg/FactorAnalytics/R/fitTsfmUpDn.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmUpDn.r 2015-03-04 18:47:01 UTC (rev 3608) +++ pkg/FactorAnalytics/R/fitTsfmUpDn.r 2015-03-06 18:46:18 UTC (rev 3609) @@ -1,6 +1,6 @@ #' @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 +#' @description This is a wrapper function to fits a up and 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 @@ -8,46 +8,11 @@ #' \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. +#' \code{fitTsfmUpDn} will use \code{fitTsfm} to fit a time series model for up and down market respectively. If +#' risk free rate is provided, the up market is the excess market returns which is no less than 0. +#' The goal of up and down marke is to capture different market Betas in the up and down markets. #' -#' 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. @@ -70,20 +35,19 @@ #' @param ... arguments passed to \code{\link{fitTsfm.control}} #' #' @return +#' \code{fitTsfmUpDn} returns an object \code{tsfmUpDn}. It supports generic function such as +#' \code{summary}, \code{predict}, \code{plot} and \code{print}. #' -#' 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. +#' It is also a list object containing \code{Up} and \code{Dn}. Both \code{Up} and \code{Dn} are class of \code{"tsfm"}. As a result, for each list +#' object, The generic function such as \code{print}, \code{plot}, \code{predict} +#' and \code{summary} methods exist for both \code{Up} and \code{Dn}. Also, the generic accessor functions \code{coef}, +#' \code{fitted} \code{residuals} and \code{fmCov} can be applied as well. #' -#' 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{"tsfmUpDn"} is a list containing \code{Up} and \code{Dn}: +#' \item{Up}{An object of \code{tsfm} fitted by \code{fitTsfm} for the up market.} +#' \item{Dn}{An object of \code{tsfm} fitted by \code{fitTsfm} for the down market.} #' -#' An object of class \code{"tsfm"} is a list containing the following -#' components: +#' Each object of \code{tsfm} contains : #' \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 @@ -109,31 +73,14 @@ #' 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. +#' @seealso +#' The \code{tsfmUpDn} methods for generic functions: +#' \code{\link{plot.tsfmUpDn}}, \code{\link{predict.tsfmUpDn}}, +#' \code{\link{print.tsfmUpDn}} and \code{\link{summary.tsfmUpDn}}. #' -#' 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. -#' +#' The original time series function \code{\link{fitTsfm}} and its generic functions +#' application. #' @examples #' # load data from the database #' data(managers) @@ -141,9 +88,12 @@ #' # 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 #' +#' print(fitUpDn) +#' summary(fitUpDn) +#' +#' # A list object +#' fitUpDn #' summary(fitUpDn$Up) #' summary(fitUpDn$Dn) #' Modified: pkg/FactorAnalytics/R/plot.tsfmUpDn.r =================================================================== --- pkg/FactorAnalytics/R/plot.tsfmUpDn.r 2015-03-04 18:47:01 UTC (rev 3608) +++ pkg/FactorAnalytics/R/plot.tsfmUpDn.r 2015-03-06 18:46:18 UTC (rev 3609) @@ -6,8 +6,8 @@ #' 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. +#' For other types of plots, use the list objects \code{Up} and \code{Dn} of class \code{tsfmUpDn}. +#' 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 Modified: pkg/FactorAnalytics/man/fitTsfm.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfm.Rd 2015-03-04 18:47:01 UTC (rev 3608) +++ pkg/FactorAnalytics/man/fitTsfm.Rd 2015-03-06 18:46:18 UTC (rev 3609) @@ -120,17 +120,9 @@ \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. +factors to be added to any of the above methods. A wrapper function +\code{\link{fitTsfmMT}} is built based on this functionality. Please refer to +\code{fitTsfmMT} for detail. \subsection{Data Processing}{ Modified: pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd 2015-03-04 18:47:01 UTC (rev 3608) +++ pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd 2015-03-06 18:46:18 UTC (rev 3609) @@ -43,14 +43,11 @@ \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. +\code{fitTsfmLagBeta} also returns an object of class \code{"tsfm"} like +\code{fitTsfm}. The generic function such as \code{print}, \code{plot}, \code{predict} +and \code{summary} methods exist. Also, the generic accessor functions \code{coef}, +\code{fitted} \code{residuals} and \code{fmCov} can be applied as well. -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 @@ -76,58 +73,18 @@ 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 +squares-DLS (or) robust regression like \code{fitTsfm}. 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. +The lagged returns model estimates lagged market Beta. Specifically, +\deqn{r_t = \alpha + \beta_0 MKT_t + \beta_1 MKT_t-1 + \ldots + \beta_K MKT_t-K + \epsilon_t, t=1 \ldots T} +where \eqn{r_t} is the asset returns, and MKT is the market factor. It is usually +needed for illiquid securities with stale prices. One can also report the sum of +the lagged Betas: +\deqn{\beta = \beta_0 + \beta_1 + \ldots + \beta_K } } -} \examples{ # load data from the database data(managers) @@ -143,33 +100,11 @@ 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. +Scholes, M. and Williams, J. T. (1977). Estimating betas from non-synchronous +data, Journal of Financial Economics, vol. 5, 1977, pp. 309-327 } \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. +The original time series function \code{\link{fitTsfm}} and its generic functions + application. } Modified: pkg/FactorAnalytics/man/fitTsfmMT.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfmMT.Rd 2015-03-04 18:47:01 UTC (rev 3608) +++ pkg/FactorAnalytics/man/fitTsfmMT.Rd 2015-03-06 18:46:18 UTC (rev 3609) @@ -40,14 +40,11 @@ \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. +\code{fitTsfmMT} also returns an object of class \code{"tsfm"} like +\code{fitTsfm}. The generic function such as \code{print}, \code{plot}, \code{predict} +and \code{summary} methods exist. Also, the generic accessor functions \code{coef}, +\code{fitted} \code{residuals} and \code{fmCov} can be applied as well. -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 @@ -78,53 +75,11 @@ \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 [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3609 From noreply at r-forge.r-project.org Wed Mar 11 02:13:15 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 11 Mar 2015 02:13:15 +0100 (CET) Subject: [Returnanalytics-commits] r3610 - in pkg/FactorAnalytics: . R man tests Message-ID: <20150311011315.DAF73186980@r-forge.r-project.org> Author: chenyian Date: 2015-03-11 02:13:15 +0100 (Wed, 11 Mar 2015) New Revision: 3610 Modified: pkg/FactorAnalytics/DESCRIPTION pkg/FactorAnalytics/R/fitTsfmLagBeta.r pkg/FactorAnalytics/R/fitTsfmMT.r pkg/FactorAnalytics/R/fitTsfmUpDn.r pkg/FactorAnalytics/R/plot.tsfmUpDn.r pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd pkg/FactorAnalytics/man/fitTsfmMT.Rd pkg/FactorAnalytics/man/fitTsfmUpDn.Rd pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd pkg/FactorAnalytics/tests/factorAnalytics.pdf Log: version 2.011. 1. Delete argument "factor.names" in fitTsfmLagBeta.r, fitTsfmMT.r and fitTsfmUpDn.r so that the function is simpler. 2. Edit document fitTsfmLagBeta.Rd, fitTsfmMT.Rd and fitTsfmUpDn.Rd. Modified: pkg/FactorAnalytics/DESCRIPTION =================================================================== --- pkg/FactorAnalytics/DESCRIPTION 2015-03-06 18:46:18 UTC (rev 3609) +++ pkg/FactorAnalytics/DESCRIPTION 2015-03-11 01:13:15 UTC (rev 3610) @@ -1,8 +1,8 @@ Package: factorAnalytics Type: Package Title: Factor Analytics -Version: 2.0.10 -Date: 2015-01-27 +Version: 2.0.11 +Date: 2015-03-10 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 Modified: pkg/FactorAnalytics/R/fitTsfmLagBeta.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmLagBeta.r 2015-03-06 18:46:18 UTC (rev 3609) +++ pkg/FactorAnalytics/R/fitTsfmLagBeta.r 2015-03-11 01:13:15 UTC (rev 3610) @@ -3,8 +3,7 @@ #' @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 like \code{fitTsfm}. Several variable selection options -#' including Stepwise, Subsets, Lars are available as well. An object of class +#' squares-DLS (or) robust regression like \code{fitTsfm}.An object of class #' \code{"tsfm"} is returned. #' #' @details @@ -17,12 +16,11 @@ #' #' @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 +#' @param mkt.name name of the column for market returns. 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. +#' excess returns for all assets (in \code{asset.names}) and the market factor (in +#' \code{mkt.name}).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 @@ -30,9 +28,6 @@ #' 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. @@ -41,27 +36,22 @@ #' @return \code{fitTsfmLagBeta} also returns an object of class \code{"tsfm"} like #' \code{fitTsfm}. The generic function such as \code{print}, \code{plot}, \code{predict} #' and \code{summary} methods exist. Also, the generic accessor functions \code{coef}, -#' \code{fitted} \code{residuals} and \code{fmCov} can be applied as well. +#' \code{fitted}, \code{residuals} and \code{fmCov} can be applied as well. #' #' 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"}.} +#' the \code{fit.method="Robust"}.} #' \item{alpha}{length-N vector of estimated alphas.} -#' \item{beta}{N x K matrix of estimated betas.} +#' \item{beta}{N x (L+1) 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 +#' Where N is the number of assets, L is the number of lagged market Betas and T is the #' number of time periods. #' #' @author Yi-An Chen. @@ -80,8 +70,7 @@ #' #' # 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) +#' mkt.name="SP500.TR",rf.name="US.3m.TR",data=managers) #' summary(fit) #' fitted(fit) #' @@ -92,9 +81,9 @@ #' #' @export -fitTsfmLagBeta <- function(asset.names, factor.names=NULL, mkt.name=NULL, rf.name=NULL, +fitTsfmLagBeta <- function(asset.names, mkt.name, rf.name=NULL, data=data, fit.method=c("OLS","DLS","Robust"),LagBeta=1, - variable.selection=c("none","stepwise","subsets","lars"), control=fitTsfm.control(...),...) { + control=fitTsfm.control(...),...) { if (is.null(mkt.name)) { stop("Missing argument: mkt.name has to be specified for lagged Betas model.") @@ -106,6 +95,7 @@ } # Create market lag terms + factor.names = mkt.name mktlag <- lag(data[,mkt.name],k=seq(1:LagBeta)) for (i in 1:LagBeta) { colnames(mktlag)[i] <- paste("MktLag",i,sep="") @@ -114,7 +104,7 @@ 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) + data=data,fit.method=fit.method,variable.selection="none",control=control) return(fit) } \ No newline at end of file Modified: pkg/FactorAnalytics/R/fitTsfmMT.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmMT.r 2015-03-06 18:46:18 UTC (rev 3609) +++ pkg/FactorAnalytics/R/fitTsfmMT.r 2015-03-11 01:13:15 UTC (rev 3610) @@ -3,8 +3,7 @@ #' @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 +#' squares-DLS (or) robust regression. An object of class #' \code{"tsfm"} is returned. #' #' @details @@ -17,20 +16,16 @@ #' #' @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 +#' @param mkt.name name of the column for market returns; 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. +#' excess returns for all assets (in \code{asset.names}) and the market factor (in +#' \code{mkt.name}).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. @@ -39,27 +34,22 @@ #' @return \code{fitTsfmMT} also returns an object of class \code{"tsfm"} like #' \code{fitTsfm}. The generic function such as \code{print}, \code{plot}, \code{predict} #' and \code{summary} methods exist. Also, the generic accessor functions \code{coef}, -#' \code{fitted} \code{residuals} and \code{fmCov} can be applied as well. +#' \code{fitted}, \code{residuals} and \code{fmCov} can be applied as well. #' #' 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"}.} +#' the \code{fit.method="Robust"}.} #' \item{alpha}{length-N vector of estimated alphas.} -#' \item{beta}{N x K matrix of estimated betas.} +#' \item{beta}{N x 2 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 +#' Where N is the number of assets and T is the #' number of time periods. #' #' @author Yi-An Chen. @@ -93,17 +83,15 @@ #' #' @export -fitTsfmMT <- function(asset.names, factor.names=NULL, mkt.name=NULL, rf.name=NULL, +fitTsfmMT <- function(asset.names,mkt.name, rf.name=NULL, data=data, fit.method=c("OLS","DLS","Robust"), - variable.selection=c("none","stepwise","subsets","lars"), control=fitTsfm.control(...),...) { + 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") + fit.Timing <- fitTsfm(asset.names=asset.names,factor.names=mkt.name,mkt.name=mkt.name,rf.name=rf.name, + data=data,fit.method=fit.method,variable.selection="none",control=control,mkt.timing="HM") return(fit.Timing) } Modified: pkg/FactorAnalytics/R/fitTsfmUpDn.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmUpDn.r 2015-03-06 18:46:18 UTC (rev 3609) +++ pkg/FactorAnalytics/R/fitTsfmUpDn.r 2015-03-11 01:13:15 UTC (rev 3610) @@ -3,32 +3,27 @@ #' @description This is a wrapper function to fits a up and 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. +#' squares-DLS (or) robust regression. An object of class +#' \code{"tsfmUpDn"} is returned. #' #' @details #' \code{fitTsfmUpDn} will use \code{fitTsfm} to fit a time series model for up and down market respectively. If #' risk free rate is provided, the up market is the excess market returns which is no less than 0. -#' The goal of up and down marke is to capture different market Betas in the up and down markets. +#' The goal of up and down market model is to capture two different market Betas in the up and down markets. #' #' #' @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 +#' @param mkt.name name of the column for market returns. 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. +#' excess returns for all assets (in \code{asset.names}) and the market factor (in +#' \code{mkt.name}). Default is \code{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. @@ -41,7 +36,7 @@ #' It is also a list object containing \code{Up} and \code{Dn}. Both \code{Up} and \code{Dn} are class of \code{"tsfm"}. As a result, for each list #' object, The generic function such as \code{print}, \code{plot}, \code{predict} #' and \code{summary} methods exist for both \code{Up} and \code{Dn}. Also, the generic accessor functions \code{coef}, -#' \code{fitted} \code{residuals} and \code{fmCov} can be applied as well. +#' \code{fitted}, \code{residuals} and \code{fmCov} can be applied as well. #' #' An object of class \code{"tsfmUpDn"} is a list containing \code{Up} and \code{Dn}: #' \item{Up}{An object of \code{tsfm} fitted by \code{fitTsfm} for the up market.} @@ -50,21 +45,17 @@ #' Each object of \code{tsfm} contains : #' \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"}.} +#' the \code{fit.method="Robust"}} #' \item{alpha}{length-N vector of estimated alphas.} -#' \item{beta}{N x K matrix of estimated betas.} +#' \item{beta}{N x 1 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 +#' Where N is the number of assets and T is the #' number of time periods. #' #' @author Yi-An Chen. @@ -105,50 +96,46 @@ #' @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(...),...) { +fitTsfmUpDn <- function(asset.names, mkt.name, rf.name=NULL, + data=data, fit.method=c("OLS","DLS","Robust"), + 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]) + dat.xts <- merge(data.xts[,asset.names], data.xts[,mkt.name]) ### 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.") + warning("The 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.") + warning("The 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, + fitUp <- fitTsfm(asset.names=asset.names,factor.names=mkt.name,mkt.name=mkt.name,rf.name=rf.name, + data=dataUp.xts,fit.method=fit.method,variable.selection="none", 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, + fitDn <- fitTsfm(asset.names=asset.names,factor.names=mkt.name,mkt.name=mkt.name,rf.name=rf.name, + data=dataDn.xts,fit.method=fit.method,variable.selection="none", control=control) result <- list(Up = fitUp, Dn = fitDn) Modified: pkg/FactorAnalytics/R/plot.tsfmUpDn.r =================================================================== --- pkg/FactorAnalytics/R/plot.tsfmUpDn.r 2015-03-06 18:46:18 UTC (rev 3609) +++ pkg/FactorAnalytics/R/plot.tsfmUpDn.r 2015-03-11 01:13:15 UTC (rev 3610) @@ -12,8 +12,8 @@ #' @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 assets.name The name of the asset used in \code{fitTsfmUpDn}. It supports one +#' asset name at once. #' @param ... Other arguments can be used in \code{plot}. #' @author Yi-An Chen #' Modified: pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd 2015-03-06 18:46:18 UTC (rev 3609) +++ pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd 2015-03-11 01:13:15 UTC (rev 3610) @@ -4,23 +4,20 @@ \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(...), ...) +fitTsfmLagBeta(asset.names, mkt.name, rf.name = NULL, data = data, + fit.method = c("OLS", "DLS", "Robust"), LagBeta = 1, + 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 +\item{mkt.name}{name of the column for market returns. 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 -\code{factor.names}). Default is NULL, and no action is taken.} +excess returns for all assets (in \code{asset.names}) and the market factor (in +\code{mkt.name}).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 @@ -32,10 +29,6 @@ \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.} @@ -46,35 +39,29 @@ \code{fitTsfmLagBeta} also returns an object of class \code{"tsfm"} like \code{fitTsfm}. The generic function such as \code{print}, \code{plot}, \code{predict} and \code{summary} methods exist. Also, the generic accessor functions \code{coef}, -\code{fitted} \code{residuals} and \code{fmCov} can be applied as well. +\code{fitted}, \code{residuals} and \code{fmCov} can be applied as well. 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"}.} +the \code{fit.method="Robust"}.} \item{alpha}{length-N vector of estimated alphas.} -\item{beta}{N x K matrix of estimated betas.} +\item{beta}{N x (L+1) 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 +Where N is the number of assets, L is the number of lagged market Betas 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 like \code{fitTsfm}. Several variable selection options -including Stepwise, Subsets, Lars are available as well. An object of class +squares-DLS (or) robust regression like \code{fitTsfm}.An object of class \code{"tsfm"} is returned. } \details{ @@ -91,8 +78,7 @@ # 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) + mkt.name="SP500.TR",rf.name="US.3m.TR",data=managers) summary(fit) fitted(fit) } Modified: pkg/FactorAnalytics/man/fitTsfmMT.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfmMT.Rd 2015-03-06 18:46:18 UTC (rev 3609) +++ pkg/FactorAnalytics/man/fitTsfmMT.Rd 2015-03-11 01:13:15 UTC (rev 3610) @@ -4,23 +4,20 @@ \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(...), ...) +fitTsfmMT(asset.names, mkt.name, rf.name = NULL, data = data, + fit.method = c("OLS", "DLS", "Robust"), 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 +\item{mkt.name}{name of the column for market returns; 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 -\code{factor.names}). Default is NULL, and no action is taken.} +excess returns for all assets (in \code{asset.names}) and the market factor (in +\code{mkt.name}).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 @@ -29,10 +26,6 @@ \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.} @@ -43,35 +36,29 @@ \code{fitTsfmMT} also returns an object of class \code{"tsfm"} like \code{fitTsfm}. The generic function such as \code{print}, \code{plot}, \code{predict} and \code{summary} methods exist. Also, the generic accessor functions \code{coef}, -\code{fitted} \code{residuals} and \code{fmCov} can be applied as well. +\code{fitted}, \code{residuals} and \code{fmCov} can be applied as well. 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"}.} +the \code{fit.method="Robust"}.} \item{alpha}{length-N vector of estimated alphas.} -\item{beta}{N x K matrix of estimated betas.} +\item{beta}{N x 2 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 +Where N is the number of assets 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 +squares-DLS (or) robust regression. An object of class \code{"tsfm"} is returned. } \details{ Modified: pkg/FactorAnalytics/man/fitTsfmUpDn.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfmUpDn.Rd 2015-03-06 18:46:18 UTC (rev 3609) +++ pkg/FactorAnalytics/man/fitTsfmUpDn.Rd 2015-03-11 01:13:15 UTC (rev 3610) @@ -4,23 +4,20 @@ \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(...), ...) +fitTsfmUpDn(asset.names, mkt.name, rf.name = NULL, data = data, + fit.method = c("OLS", "DLS", "Robust"), 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 +\item{mkt.name}{name of the column for market returns. 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.} +excess returns for all assets (in \code{asset.names}) and the market factor (in +\code{mkt.name}). Default is \code{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 @@ -29,10 +26,6 @@ \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.} @@ -46,7 +39,7 @@ It is also a list object containing \code{Up} and \code{Dn}. Both \code{Up} and \code{Dn} are class of \code{"tsfm"}. As a result, for each list object, The generic function such as \code{print}, \code{plot}, \code{predict} and \code{summary} methods exist for both \code{Up} and \code{Dn}. Also, the generic accessor functions \code{coef}, -\code{fitted} \code{residuals} and \code{fmCov} can be applied as well. +\code{fitted}, \code{residuals} and \code{fmCov} can be applied as well. An object of class \code{"tsfmUpDn"} is a list containing \code{Up} and \code{Dn}: \item{Up}{An object of \code{tsfm} fitted by \code{fitTsfm} for the up market.} @@ -55,35 +48,30 @@ Each object of \code{tsfm} contains : \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"}.} +the \code{fit.method="Robust"}} \item{alpha}{length-N vector of estimated alphas.} -\item{beta}{N x K matrix of estimated betas.} +\item{beta}{N x 1 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 +Where N is the number of assets and T is the number of time periods. } \description{ This is a wrapper function to fits a up and 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. +squares-DLS (or) robust regression. An object of class [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3610 From noreply at r-forge.r-project.org Sun Mar 15 17:39:29 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 15 Mar 2015 17:39:29 +0100 (CET) Subject: [Returnanalytics-commits] r3611 - in pkg/FactorAnalytics: R man Message-ID: <20150315163929.BA061186B01@r-forge.r-project.org> Author: pragnya Date: 2015-03-15 17:39:29 +0100 (Sun, 15 Mar 2015) New Revision: 3611 Modified: pkg/FactorAnalytics/R/fitTsfm.R pkg/FactorAnalytics/man/fitTsfm.Rd Log: Removed warning about excess returns in fitTsfm Modified: pkg/FactorAnalytics/R/fitTsfm.R =================================================================== --- pkg/FactorAnalytics/R/fitTsfm.R 2015-03-11 01:13:15 UTC (rev 3610) +++ pkg/FactorAnalytics/R/fitTsfm.R 2015-03-15 16:39:29 UTC (rev 3611) @@ -1,572 +1,570 @@ -#' @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. A wrapper function -#' \code{\link{fitTsfmMT}} is built based on this functionality. Please refer to -#' \code{fitTsfmMT} for detail. -#' -#' \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 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 <- 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" - 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. A wrapper function +#' \code{\link{fitTsfmMT}} is built based on this functionality. Please refer to +#' \code{fitTsfmMT} for detail. +#' +#' \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 using "subsets" variable selection +#' fit.sub <- fitTsfm(asset.names=colnames(managers[,(1:6)]), +#' factor.names=colnames(managers[,(7:9)]), +#' data=managers, variable.selection="subsets", [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3611 From noreply at r-forge.r-project.org Sun Mar 15 18:06:23 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 15 Mar 2015 18:06:23 +0100 (CET) Subject: [Returnanalytics-commits] r3612 - in pkg/FactorAnalytics: R man vignettes Message-ID: <20150315170623.5CBA3187698@r-forge.r-project.org> Author: pragnya Date: 2015-03-15 18:06:23 +0100 (Sun, 15 Mar 2015) New Revision: 3612 Modified: pkg/FactorAnalytics/R/fitTsfm.R pkg/FactorAnalytics/man/print.pafm.Rd pkg/FactorAnalytics/man/print.sfm.Rd pkg/FactorAnalytics/man/print.tsfm.Rd pkg/FactorAnalytics/man/print.tsfmUpDn.Rd pkg/FactorAnalytics/man/summary.pafm.Rd pkg/FactorAnalytics/man/summary.sfm.Rd pkg/FactorAnalytics/man/summary.tsfm.Rd pkg/FactorAnalytics/man/summary.tsfmUpDn.Rd pkg/FactorAnalytics/vignettes/fitSfm_vignette.Rnw pkg/FactorAnalytics/vignettes/fitTsfm_vignette.Rnw Log: Removed warning about excess returns in fitTsfm Modified: pkg/FactorAnalytics/R/fitTsfm.R =================================================================== --- pkg/FactorAnalytics/R/fitTsfm.R 2015-03-15 16:39:29 UTC (rev 3611) +++ pkg/FactorAnalytics/R/fitTsfm.R 2015-03-15 17:06:23 UTC (rev 3612) @@ -189,10 +189,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/man/print.pafm.Rd =================================================================== --- pkg/FactorAnalytics/man/print.pafm.Rd 2015-03-15 16:39:29 UTC (rev 3611) +++ pkg/FactorAnalytics/man/print.pafm.Rd 2015-03-15 17:06:23 UTC (rev 3612) @@ -1,30 +1,29 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/print.pafm.r -\name{print.pafm} -\alias{print.pafm} -\title{Print object of class \code{"pafm"}.} -\usage{ -\method{print}{pafm}(x, ...) -} -\arguments{ -\item{x}{object of class \code{"pafm"} created by -\code{paFm}.} - -\item{...}{Other arguments for \code{print} methods.} -} -\description{ -Generic function of print method for \code{paFm}. -} -\examples{ -# load data from the database - data(managers) -# fit the factor model with OLS -fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), - factor.names=c("EDHEC.LS.EQ","SP500.TR"), data=managers) -fm.attr <- paFm(fit) -print(fm.attr) -} -\author{ -Yi-An Chen. -} - +% Generated by roxygen2 (4.0.2): do not edit by hand +\name{print.pafm} +\alias{print.pafm} +\title{Print object of class \code{"pafm"}.} +\usage{ +\method{print}{pafm}(x, ...) +} +\arguments{ +\item{x}{object of class \code{"pafm"} created by +\code{paFm}.} + +\item{...}{Other arguments for \code{print} methods.} +} +\description{ +Generic function of print method for \code{paFm}. +} +\examples{ +# load data from the database + data(managers) +# fit the factor model with OLS +fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), + factor.names=c("EDHEC.LS.EQ","SP500.TR"), data=managers) +fm.attr <- paFm(fit) +print(fm.attr) +} +\author{ +Yi-An Chen. +} + Modified: pkg/FactorAnalytics/man/print.sfm.Rd =================================================================== --- pkg/FactorAnalytics/man/print.sfm.Rd 2015-03-15 16:39:29 UTC (rev 3611) +++ pkg/FactorAnalytics/man/print.sfm.Rd 2015-03-15 17:06:23 UTC (rev 3612) @@ -1,33 +1,32 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/print.sfm.r -\name{print.sfm} -\alias{print.sfm} -\title{Prints out a fitted statictical factor model object} -\usage{ -\method{print}{sfm}(x, digits = max(3, .Options$digits - 3), ...) -} -\arguments{ -\item{x}{an object of class \code{sfm} produced by \code{fitSfm}.} - -\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{sfm}. Prints -the call, factor model dimension, factor loadings, r-squared and residual -volatilities from the fitted object. -} -\examples{ -data(StockReturns) -fit <- fitSfm(r.M, k=2) -print(fit) -} -\author{ -Yi-An Chen and Sangeetha Srinivasan -} -\seealso{ -\code{\link{fitSfm}}, \code{\link{summary.sfm}} -} - +% Generated by roxygen2 (4.0.2): do not edit by hand +\name{print.sfm} +\alias{print.sfm} +\title{Prints out a fitted statictical factor model object} +\usage{ +\method{print}{sfm}(x, digits = max(3, .Options$digits - 3), ...) +} +\arguments{ +\item{x}{an object of class \code{sfm} produced by \code{fitSfm}.} + +\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{sfm}. Prints +the call, factor model dimension, factor loadings, r-squared and residual +volatilities from the fitted object. +} +\examples{ +data(StockReturns) +fit <- fitSfm(r.M, k=2) +print(fit) +} +\author{ +Yi-An Chen and Sangeetha Srinivasan +} +\seealso{ +\code{\link{fitSfm}}, \code{\link{summary.sfm}} +} + Modified: pkg/FactorAnalytics/man/print.tsfm.Rd =================================================================== --- pkg/FactorAnalytics/man/print.tsfm.Rd 2015-03-15 16:39:29 UTC (rev 3611) +++ pkg/FactorAnalytics/man/print.tsfm.Rd 2015-03-15 17:06:23 UTC (rev 3612) @@ -1,35 +1,34 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/print.tsfm.r -\name{print.tsfm} -\alias{print.tsfm} -\title{Prints out a fitted time series factor model object} -\usage{ -\method{print}{tsfm}(x, digits = max(3, .Options$digits - 3), ...) -} -\arguments{ -\item{x}{an object of class \code{tsfm} produced by \code{fitTsfm}.} - -\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{tsfm}. Prints -the call, factor model dimension, regression coefficients, r-squared and -residual volatilities from the fitted object. -} -\examples{ -data(managers) -fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), - factor.names=colnames(managers[,7:9]), - mkt.name="SP500.TR", mkt.timing="both", data=managers) -print(fit) -} -\author{ -Yi-An Chen and Sangeetha Srinivasan -} -\seealso{ -\code{\link{fitTsfm}}, \code{\link{summary.tsfm}} -} - +% Generated by roxygen2 (4.0.2): do not edit by hand +\name{print.tsfm} +\alias{print.tsfm} +\title{Prints out a fitted time series factor model object} +\usage{ +\method{print}{tsfm}(x, digits = max(3, .Options$digits - 3), ...) +} +\arguments{ +\item{x}{an object of class \code{tsfm} produced by \code{fitTsfm}.} + +\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{tsfm}. Prints +the call, factor model dimension, regression coefficients, r-squared and +residual volatilities from the fitted object. +} +\examples{ +data(managers) +fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), + factor.names=colnames(managers[,7:9]), + mkt.name="SP500.TR", mkt.timing="both", data=managers) +print(fit) +} +\author{ +Yi-An Chen and Sangeetha Srinivasan +} +\seealso{ +\code{\link{fitTsfm}}, \code{\link{summary.tsfm}} +} + Modified: pkg/FactorAnalytics/man/print.tsfmUpDn.Rd =================================================================== --- pkg/FactorAnalytics/man/print.tsfmUpDn.Rd 2015-03-15 16:39:29 UTC (rev 3611) +++ pkg/FactorAnalytics/man/print.tsfmUpDn.Rd 2015-03-15 17:06:23 UTC (rev 3612) @@ -1,36 +1,35 @@ -% 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}} -} - +% Generated by roxygen2 (4.0.2): do not edit by hand +\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.pafm.Rd =================================================================== --- pkg/FactorAnalytics/man/summary.pafm.Rd 2015-03-15 16:39:29 UTC (rev 3611) +++ pkg/FactorAnalytics/man/summary.pafm.Rd 2015-03-15 17:06:23 UTC (rev 3612) @@ -1,34 +1,33 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/summary.pafm.r -\name{summary.pafm} -\alias{summary.pafm} -\title{summary \code{"pafm"} object.} -\usage{ -\method{summary}{pafm}(object, digits = max(3, .Options$digits - 3), ...) -} -\arguments{ -\item{object}{\code{"pafm"} object created by -\code{paFm}.} - -\item{digits}{integer indicating the number of decimal places. Default is 3.} - -\item{...}{Other arguments for \code{print} methods.} -} -\description{ -Generic function of summary method for \code{paFm}. -} -\examples{ -# load data from the database -data(managers) -# fit the factor model with OLS -fit.ts <- fitTsfm(asset.names=colnames(managers[,(1:6)]), - factor.names=c("EDHEC.LS.EQ","SP500.TR"), - data=managers) - -fm.attr <- paFm(fit.ts) -summary(fm.attr) -} -\author{ -Yi-An Chen. -} - +% Generated by roxygen2 (4.0.2): do not edit by hand +\name{summary.pafm} +\alias{summary.pafm} +\title{summary \code{"pafm"} object.} +\usage{ +\method{summary}{pafm}(object, digits = max(3, .Options$digits - 3), ...) +} +\arguments{ +\item{object}{\code{"pafm"} object created by +\code{paFm}.} + +\item{digits}{integer indicating the number of decimal places. Default is 3.} + +\item{...}{Other arguments for \code{print} methods.} +} +\description{ +Generic function of summary method for \code{paFm}. +} +\examples{ +# load data from the database +data(managers) +# fit the factor model with OLS +fit.ts <- fitTsfm(asset.names=colnames(managers[,(1:6)]), + factor.names=c("EDHEC.LS.EQ","SP500.TR"), + data=managers) + +fm.attr <- paFm(fit.ts) +summary(fm.attr) +} +\author{ +Yi-An Chen. +} + Modified: pkg/FactorAnalytics/man/summary.sfm.Rd =================================================================== --- pkg/FactorAnalytics/man/summary.sfm.Rd 2015-03-15 16:39:29 UTC (rev 3611) +++ pkg/FactorAnalytics/man/summary.sfm.Rd 2015-03-15 17:06:23 UTC (rev 3612) @@ -1,70 +1,69 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/summary.sfm.r -\name{summary.sfm} -\alias{print.summary.sfm} -\alias{summary.sfm} -\title{Summarizing a fitted time series factor model} -\usage{ -\method{summary}{sfm}(object, se.type = c("Default", "HC", "HAC"), - n.top = 3, ...) - -\method{print}{summary.sfm}(x, digits = 3, ...) -} -\arguments{ -\item{object}{an object of class \code{sfm} returned by \code{fitSfm}.} - -\item{se.type}{one of "Default", "HC" or "HAC"; option for computing HC/HAC -standard errors and t-statistics. Default is "Default".} - -\item{n.top}{scalar; number of largest and smallest weights to display for -each factor mimicking portfolio. Default is 3.} - -\item{...}{futher arguments passed to or from other methods.} - -\item{x}{an object of class \code{summary.sfm}.} - -\item{digits}{number of significants digits to use when printing. -Default is 3.} -} -\value{ -Returns an object of class \code{summary.sfm}. -The print method for class \code{summary.sfm} outputs the call, -coefficients (with standard errors and t-statistics), r-squared and -residual volatilty (under the homoskedasticity assumption) for all assets as -well as a summary of the factor mimicking portfolio weights. - -Object of class \code{summary.sfm} is a list of length N+2 containing: -\item{call}{the function call to \code{fitSfm}} -\item{se.type}{standard error type as input} -\item{sum.list}{list of summaries for the N fit objects of class \code{lm} -for each asset in the factor model.} -\item{mimic.sum}{list of data.frame objects containing \code{n.top} largest -and smallest weights for each factor mimicking portfolio.} -} -\description{ -\code{summary} method for object of class \code{sfm}. -Returned object is of class {summary.sfm}. -} -\details{ -The default \code{summary} method for a fitted \code{lm} object -computes the standard errors and t-statistics under the assumption of -homoskedasticty. Argument \code{se.type} gives the option to compute -heteroskedasticity-consistent (HC) or -heteroskedasticity-autocorrelation-consistent (HAC) standard errors and -t-statistics using \code{\link[lmtest]{coeftest}}. -} -\examples{ -data(StockReturns) -# fit the factor model with PCA -fit <- fitSfm(r.M, k=2) - -# summary of factor model fit for all assets -summary(fit, "HAC") -} -\author{ -Sangeetha Srinivasan -} -\seealso{ -\code{\link{fitSfm}}, \code{\link[stats]{summary.lm}} -} - +% Generated by roxygen2 (4.0.2): do not edit by hand +\name{summary.sfm} +\alias{print.summary.sfm} +\alias{summary.sfm} +\title{Summarizing a fitted time series factor model} +\usage{ +\method{summary}{sfm}(object, se.type = c("Default", "HC", "HAC"), + n.top = 3, ...) + +\method{print}{summary.sfm}(x, digits = 3, ...) +} +\arguments{ +\item{object}{an object of class \code{sfm} returned by \code{fitSfm}.} + +\item{se.type}{one of "Default", "HC" or "HAC"; option for computing HC/HAC +standard errors and t-statistics. Default is "Default".} + +\item{n.top}{scalar; number of largest and smallest weights to display for +each factor mimicking portfolio. Default is 3.} + +\item{...}{futher arguments passed to or from other methods.} + +\item{x}{an object of class \code{summary.sfm}.} + +\item{digits}{number of significants digits to use when printing. +Default is 3.} +} +\value{ +Returns an object of class \code{summary.sfm}. +The print method for class \code{summary.sfm} outputs the call, +coefficients (with standard errors and t-statistics), r-squared and +residual volatilty (under the homoskedasticity assumption) for all assets as +well as a summary of the factor mimicking portfolio weights. + +Object of class \code{summary.sfm} is a list of length N+2 containing: +\item{call}{the function call to \code{fitSfm}} +\item{se.type}{standard error type as input} +\item{sum.list}{list of summaries for the N fit objects of class \code{lm} +for each asset in the factor model.} +\item{mimic.sum}{list of data.frame objects containing \code{n.top} largest +and smallest weights for each factor mimicking portfolio.} +} +\description{ +\code{summary} method for object of class \code{sfm}. +Returned object is of class {summary.sfm}. +} +\details{ +The default \code{summary} method for a fitted \code{lm} object +computes the standard errors and t-statistics under the assumption of +homoskedasticty. Argument \code{se.type} gives the option to compute +heteroskedasticity-consistent (HC) or +heteroskedasticity-autocorrelation-consistent (HAC) standard errors and +t-statistics using \code{\link[lmtest]{coeftest}}. +} +\examples{ +data(StockReturns) +# fit the factor model with PCA +fit <- fitSfm(r.M, k=2) + +# summary of factor model fit for all assets +summary(fit, "HAC") +} +\author{ +Sangeetha Srinivasan +} +\seealso{ +\code{\link{fitSfm}}, \code{\link[stats]{summary.lm}} +} + Modified: pkg/FactorAnalytics/man/summary.tsfm.Rd =================================================================== --- pkg/FactorAnalytics/man/summary.tsfm.Rd 2015-03-15 16:39:29 UTC (rev 3611) +++ pkg/FactorAnalytics/man/summary.tsfm.Rd 2015-03-15 17:06:23 UTC (rev 3612) @@ -1,73 +1,72 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/summary.tsfm.r -\name{summary.tsfm} -\alias{print.summary.tsfm} -\alias{summary.tsfm} -\title{Summarizing a fitted time series factor model} -\usage{ -\method{summary}{tsfm}(object, se.type = c("Default", "HC", "HAC"), ...) - -\method{print}{summary.tsfm}(x, digits = 3, ...) -} -\arguments{ -\item{object}{an object of class \code{tsfm} returned by \code{fitTsfm}.} - -\item{se.type}{one of "Default", "HC" or "HAC"; option for computing -HC/HAC standard errors and t-statistics. Default is "Default".} - -\item{...}{futher arguments passed to or from other methods.} - -\item{x}{an object of class \code{summary.tsfm}.} - -\item{digits}{number of significants digits to use when printing. -Default is 3.} -} -\value{ -Returns an object of class \code{summary.tsfm}. -The print method for class \code{summary.tsfm} outputs the call, -coefficients (with standard errors and t-statistics), r-squared and -residual volatilty (under the homoskedasticity assumption) for all assets. - -Object of class \code{summary.tsfm} is a list of length N + 2 containing: -\item{call}{the function call to \code{fitTsfm}} -\item{se.type}{standard error type as input} -\item{sum.list}{list of summaries of the N fit objects (of class \code{lm}, -\code{lmRob} or \code{lars}) for each asset in the factor model.} -} -\description{ -\code{summary} method for object of class \code{tsfm}. -Returned object is of class {summary.tsfm}. -} -\details{ -The default \code{summary} method for a fitted \code{lm} object -computes the standard errors and t-statistics under the assumption of -homoskedasticty. Argument \code{se.type} gives the option to compute -heteroskedasticity-consistent (HC) or -heteroskedasticity-autocorrelation-consistent (HAC) standard errors and -t-statistics using \code{\link[lmtest]{coeftest}}. This option is meaningful -only if \code{fit.method = "OLS" or "DLS"}. - -Standard errors are currently not available for -\code{variable.selection="lars"} as there seems to be no consensus on a -statistically valid method of calculating standard errors for the lasso -predictions. -} -\examples{ -data(managers) -fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), - factor.names=colnames(managers[,7:9]), - data=managers) - -# summary of factor model fit for all assets -summary(fit, "HAC") - -# summary of lm fit for a single asset -summary(fit$asset.fit[[1]]) -} -\author{ -Sangeetha Srinivasan & Yi-An Chen. -} -\seealso{ -\code{\link{fitTsfm}}, \code{\link[stats]{summary.lm}} -} - +% Generated by roxygen2 (4.0.2): do not edit by hand +\name{summary.tsfm} +\alias{print.summary.tsfm} +\alias{summary.tsfm} +\title{Summarizing a fitted time series factor model} +\usage{ +\method{summary}{tsfm}(object, se.type = c("Default", "HC", "HAC"), ...) + +\method{print}{summary.tsfm}(x, digits = 3, ...) +} +\arguments{ +\item{object}{an object of class \code{tsfm} returned by \code{fitTsfm}.} + +\item{se.type}{one of "Default", "HC" or "HAC"; option for computing +HC/HAC standard errors and t-statistics. Default is "Default".} + +\item{...}{futher arguments passed to or from other methods.} + +\item{x}{an object of class \code{summary.tsfm}.} + +\item{digits}{number of significants digits to use when printing. +Default is 3.} +} +\value{ +Returns an object of class \code{summary.tsfm}. +The print method for class \code{summary.tsfm} outputs the call, +coefficients (with standard errors and t-statistics), r-squared and +residual volatilty (under the homoskedasticity assumption) for all assets. + +Object of class \code{summary.tsfm} is a list of length N + 2 containing: +\item{call}{the function call to \code{fitTsfm}} +\item{se.type}{standard error type as input} +\item{sum.list}{list of summaries of the N fit objects (of class \code{lm}, +\code{lmRob} or \code{lars}) for each asset in the factor model.} +} +\description{ +\code{summary} method for object of class \code{tsfm}. +Returned object is of class {summary.tsfm}. +} +\details{ +The default \code{summary} method for a fitted \code{lm} object +computes the standard errors and t-statistics under the assumption of +homoskedasticty. Argument \code{se.type} gives the option to compute +heteroskedasticity-consistent (HC) or +heteroskedasticity-autocorrelation-consistent (HAC) standard errors and +t-statistics using \code{\link[lmtest]{coeftest}}. This option is meaningful +only if \code{fit.method = "OLS" or "DLS"}. + +Standard errors are currently not available for +\code{variable.selection="lars"} as there seems to be no consensus on a +statistically valid method of calculating standard errors for the lasso +predictions. +} +\examples{ +data(managers) +fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), + factor.names=colnames(managers[,7:9]), + data=managers) + +# summary of factor model fit for all assets +summary(fit, "HAC") + +# summary of lm fit for a single asset +summary(fit$asset.fit[[1]]) +} +\author{ +Sangeetha Srinivasan & Yi-An Chen. +} +\seealso{ +\code{\link{fitTsfm}}, \code{\link[stats]{summary.lm}} +} + Modified: pkg/FactorAnalytics/man/summary.tsfmUpDn.Rd =================================================================== --- pkg/FactorAnalytics/man/summary.tsfmUpDn.Rd 2015-03-15 16:39:29 UTC (rev 3611) +++ pkg/FactorAnalytics/man/summary.tsfmUpDn.Rd 2015-03-15 17:06:23 UTC (rev 3612) @@ -1,61 +1,60 @@ -% 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 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. -} -\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 and Sangeetha Srinivasan. -} -\seealso{ -\code{\link{fitTsfmUpDn}}, \code{\link[stats]{summary.tsfm}} -} - +% Generated by roxygen2 (4.0.2): do not edit by hand +\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 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. +} +\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 and Sangeetha Srinivasan. +} +\seealso{ +\code{\link{fitTsfmUpDn}}, \code{\link[stats]{summary.tsfm}} +} + Modified: pkg/FactorAnalytics/vignettes/fitSfm_vignette.Rnw =================================================================== --- pkg/FactorAnalytics/vignettes/fitSfm_vignette.Rnw 2015-03-15 16:39:29 UTC (rev 3611) +++ pkg/FactorAnalytics/vignettes/fitSfm_vignette.Rnw 2015-03-15 17:06:23 UTC (rev 3612) @@ -114,9 +114,9 @@ \newpage \section{Fit a statistical factor model} -In statistical factor models, factor realizations are not directly observable (unlike times series factor models) and the factor loadings are not known (unlike fundamental factor models). Both factors and betas must be extracted from the returns data using statistical methods such as factor analysis and Principal Component Analysis (PCA). PCA uses the eigen decomposition of the covariance (or correlation) matrix of asset returns to find the first \code{K} principal components that explain the largest portion of the sample covariance matrix of returns. Factor loadings are then estimated using time series regression. Factor analysis involves maximum likelihood optimization to estimate the factor loadings and the residual covariance matrix, constructing the factor realizations and choosing a rotation of the coordinate system for a more meaningful interpretation of the factors. +In statistical factor models, factor realizations are not directly observable (unlike times series factor models) and the factor loadings are not known (unlike some fundamental factor models). Both factors and betas must be extracted from the returns data using statistical methods such as factor analysis or Principal Component Analysis (PCA). PCA uses the eigen decomposition of the covariance (or correlation) matrix of asset returns to find the first \code{K} principal components that explain the largest portion of the sample covariance matrix of returns. Factor loadings are then estimated using time series regression. Factor analysis involves maximum likelihood optimization to estimate the factor loadings and the residual covariance matrix, constructing the factor realizations and choosing a rotation of the coordinate system for a more meaningful interpretation of the factors. -In \code{fitSfm}, PCA is applied to extract the factor realizations when the number of time series observations, $T$, is greater than the number of assets, $N$. When $N > T$, the sample covariance matrix for asset returns is singular and Aymptotic principal Component Analysis (APCA) as in \citet{connor1988risk} is performed. +In \code{fitSfm}, PCA is applied to extract the factor realizations when the number of time series observations, $T$, is greater than the number of assets, $N$. When $N > T$, the sample covariance matrix for asset returns is singular and Aymptotic principal Component Analysis (APCA) due to \citet{connor1988risk} is performed. Let's take a look at the arguments for \code{fitSfm}. Modified: pkg/FactorAnalytics/vignettes/fitTsfm_vignette.Rnw =================================================================== --- pkg/FactorAnalytics/vignettes/fitTsfm_vignette.Rnw 2015-03-15 16:39:29 UTC (rev 3611) +++ pkg/FactorAnalytics/vignettes/fitTsfm_vignette.Rnw 2015-03-15 17:06:23 UTC (rev 3612) @@ -464,7 +464,7 @@ \newpage \subsection{Individual plots} -Setting \code{plot.single=TRUE} enables individual asset plots. If there is more than one asset fit by the fit object, \code{asset.name} is also necessary. However, if the \code{fitSfm} object \code{x} only contains one asset's factor model fit, \code{plot.sfm} can infer this automatically, without user input. +Setting \code{plot.single=TRUE} enables individual asset plots. If there is more than one asset fit by the fit object, \code{asset.name} is also necessary. However, if the \code{fitTsfm} object \code{x} only contains one asset's factor model fit, \code{plot.tsfm} can infer \code{asset.name} automatically, without user input. Here's the individual plot menu. <>= From noreply at r-forge.r-project.org Sun Mar 15 20:34:36 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 15 Mar 2015 20:34:36 +0100 (CET) Subject: [Returnanalytics-commits] r3613 - in pkg/FactorAnalytics: . R man vignettes Message-ID: <20150315193436.2BC5818784D@r-forge.r-project.org> Author: pragnya Date: 2015-03-15 20:34:35 +0100 (Sun, 15 Mar 2015) New Revision: 3613 Modified: pkg/FactorAnalytics/DESCRIPTION pkg/FactorAnalytics/NAMESPACE pkg/FactorAnalytics/R/fitTsfm.R pkg/FactorAnalytics/R/plot.tsfm.r pkg/FactorAnalytics/man/CornishFisher.Rd pkg/FactorAnalytics/man/fitSfm.Rd pkg/FactorAnalytics/man/fitTsfm.Rd pkg/FactorAnalytics/man/fitTsfm.control.Rd pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd pkg/FactorAnalytics/man/fitTsfmMT.Rd pkg/FactorAnalytics/man/fitTsfmUpDn.Rd pkg/FactorAnalytics/man/fmCov.Rd pkg/FactorAnalytics/man/fmEsDecomp.Rd pkg/FactorAnalytics/man/fmSdDecomp.Rd pkg/FactorAnalytics/man/fmVaRDecomp.Rd pkg/FactorAnalytics/man/paFm.Rd pkg/FactorAnalytics/man/plot.pafm.Rd pkg/FactorAnalytics/man/plot.sfm.Rd pkg/FactorAnalytics/man/plot.tsfm.Rd pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd pkg/FactorAnalytics/man/predict.sfm.Rd pkg/FactorAnalytics/man/predict.tsfm.Rd pkg/FactorAnalytics/man/predict.tsfmUpDn.Rd pkg/FactorAnalytics/vignettes/fitTsfm_vignette.R pkg/FactorAnalytics/vignettes/fitTsfm_vignette.Rnw pkg/FactorAnalytics/vignettes/fitTsfm_vignette.pdf Log: plot.tsfm - added 3 plot options, simplified looping, vector input for which Modified: pkg/FactorAnalytics/DESCRIPTION =================================================================== --- pkg/FactorAnalytics/DESCRIPTION 2015-03-15 17:06:23 UTC (rev 3612) +++ pkg/FactorAnalytics/DESCRIPTION 2015-03-15 19:34:35 UTC (rev 3613) @@ -1,36 +1,36 @@ -Package: factorAnalytics -Type: Package -Title: Factor Analytics -Version: 2.0.11 -Date: 2015-03-10 -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.12 +Date: 2015-03-15 +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/NAMESPACE =================================================================== --- pkg/FactorAnalytics/NAMESPACE 2015-03-15 17:06:23 UTC (rev 3612) +++ pkg/FactorAnalytics/NAMESPACE 2015-03-15 19:34:35 UTC (rev 3613) @@ -1,70 +1,70 @@ -# 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(plot,tsfmUpDn) -S3method(predict,sfm) -S3method(predict,tsfm) -S3method(predict,tsfmUpDn) -S3method(print,pafm) -S3method(print,sfm) -S3method(print,summary.sfm) -S3method(print,summary.tsfm) -S3method(print,summary.tsfmUpDn) -S3method(print,tsfm) -S3method(print,tsfmUpDn) -S3method(residuals,sfm) -S3method(residuals,tsfm) -S3method(summary,pafm) -S3method(summary,sfm) -S3method(summary,tsfm) -S3method(summary,tsfmUpDn) -export(dCornishFisher) -export(fitSfm) -export(fitTsfm) -export(fitTsfmMT) -export(fitTsfmLagBeta) -export(fitTsfmUpDn) -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(plot,tsfmUpDn) +S3method(predict,sfm) +S3method(predict,tsfm) +S3method(predict,tsfmUpDn) +S3method(print,pafm) +S3method(print,sfm) +S3method(print,summary.sfm) +S3method(print,summary.tsfm) +S3method(print,summary.tsfmUpDn) +S3method(print,tsfm) +S3method(print,tsfmUpDn) +S3method(residuals,sfm) +S3method(residuals,tsfm) +S3method(summary,pafm) +S3method(summary,sfm) +S3method(summary,tsfm) +S3method(summary,tsfmUpDn) +export(dCornishFisher) +export(fitSfm) +export(fitTsfm) +export(fitTsfmLagBeta) +export(fitTsfmMT) +export(fitTsfmUpDn) +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-03-15 17:06:23 UTC (rev 3612) +++ pkg/FactorAnalytics/R/fitTsfm.R 2015-03-15 19:34:35 UTC (rev 3613) @@ -142,8 +142,7 @@ #' 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) +#' plot(fit, plot.single=TRUE, asset.name="HAM1", which=1) #' # group plot; type selected from menu prompt; auto-looped for multiple plots #' # plot(fit) #' Modified: pkg/FactorAnalytics/R/plot.tsfm.r =================================================================== --- pkg/FactorAnalytics/R/plot.tsfm.r 2015-03-15 17:06:23 UTC (rev 3612) +++ pkg/FactorAnalytics/R/plot.tsfm.r 2015-03-15 19:34:35 UTC (rev 3613) @@ -1,430 +1,462 @@ -#' @title Plots from a fitted time series factor model -#' -#' @description Generic \code{plot} method for object of class \code{tsfm}. -#' Plots chosen characteristic(s) for one or more assets. -#' -#' @details -#' If the plot type argument is not specified, a menu prompts for user input -#' and the corresponding plot is output. And, the menu is repeated for -#' user convenience in plotting multiple characteristics. Selecting '0' from -#' the menu exits the current \code{plot.tsfm} call. Alternately, setting -#' \code{loop=FALSE} will exit after plotting any one chosen characteristic -#' without the need for menu selection. -#' -#' For group plots (the default), the first \code{max.show} assets are plotted. -#' For individual plots, \code{asset.name} is necessary if multiple assets -#' were modeled in \code{x} and \code{plot.single=TRUE}. However, if the -#' \code{fitTsfm} object contains only one asset's factor model fit, -#' \code{plot.tsfm} can infer this automatically, without user input. -#' -#' CUSUM plots (individual asset plot options 10, 11 and 12) are applicable -#' only for \code{fit.method="OLS"}. -#' -#' Rolling estimates (individual asset plot option 13) is not applicable for -#' \code{variable.slection="lars"}. -#' -#' @param x an object of class \code{tsfm} produced by \code{fitTsfm}. -#' @param which.plot.group a number to indicate the type of group plot for -#' multiple assets. If \code{NULL} (default), the following menu appears: \cr -#' 1 = Factor model coefficients: Alpha, \cr -#' 2 = Factor model coefficients: Betas, \cr -#' 3 = Actual and Fitted asset returns, \cr -#' 4 = R-squared, \cr -#' 5 = Residual Volatility,\cr -#' 6 = Factor Model Residual Correlation \cr -#' 7 = Factor Model Correlation,\cr -#' 8 = Factor Contribution to SD,\cr -#' 9 = Factor Contribution to ES,\cr -#' 10 = Factor Contribution to VaR -#' @param max.show maximum number of assets in a given plot. Default is 6. -#' @param plot.single logical; If \code{TRUE} plots the characteristics of an -#' individual asset's factor model. The type of plot is given by -#' \code{which.plot.single}. Default is \code{FALSE}. -#' @param asset.name name of the individual asset to be plotted. Is necessary -#' if \code{x} contains multiple asset fits and \code{plot.single=TRUE}. -#' @param which.plot.single a number to indicate the type of group plot for an -#' individual asset. If \code{NULL} (default), the following menu appears: \cr -#' 1 = Time series plot of actual and fitted asset returns,\cr -#' 2 = Time series plot of residuals with standard error bands, \cr -#' 3 = Time series plot of squared residuals, \cr -#' 4 = Time series plot of absolute residuals,\cr -#' 5 = SACF and PACF of residuals,\cr -#' 6 = SACF and PACF of squared residuals,\cr -#' 7 = SACF and PACF of absolute residuals,\cr -#' 8 = Histogram of residuals with normal curve overlayed,\cr -#' 9 = Normal qq-plot of residuals,\cr -#' 10 = CUSUM test-Recursive residuals,\cr -#' 11 = CUSUM test-OLS residuals,\cr -#' 12 = Recursive estimates (RE) test of OLS regression coefficients,\cr -#' 13 = Rolling estimates over a 24-period observation window -#' @param colorset color palette to use for all the plots. Default is -#' \code{c(1:12)}. The 1st element will be used for individual time series -#' plots or the 1st series plotted, the 2nd element for the 2nd object in the -#' plot and so on. -#' @param legend.loc places a legend into one of nine locations on the chart: -#' "bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", -#' "right", or "center". Default is "bottomright". Use \code{legend.loc=NULL} -#' to suppress the legend. -#' @param las one of {0, 1, 2, 3} to set the direction of axis labels, same as -#' in \code{plot}. Default here is 1. -#' @param VaR.method a method for computing VaR; one of "modified", "gaussian", -#' "historical" or "kernel". VaR is computed using -#' \code{\link[PerformanceAnalytics]{VaR}}. Default is "historical". -#' @param loop logical to indicate if the plot menu should be repeated. Default -#' is \code{TRUE}. -#' @param ... further arguments to be passed to other plotting functions. -#' -#' @author Eric Zivot, Sangeetha Srinivasan and Yi-An Chen -#' -#' @seealso \code{\link{fitTsfm}} and \code{\link{summary.tsfm}} for details -#' about the time series factor model fit, extractor functions and summary -#' statistics. -#' -#' \code{\link[strucchange]{efp}} for CUSUM tests. -#' -#' \code{\link[xts]{plot.xts}}, -#' \code{\link[PerformanceAnalytics]{chart.TimeSeries}}, -#' \code{\link[PerformanceAnalytics]{chart.ACFplus}}, -#' \code{\link[PerformanceAnalytics]{chart.Histogram}}, -#' \code{\link[PerformanceAnalytics]{chart.QQPlot}}, -#' \code{\link[graphics]{barplot}}, \code{\link[lattice]{barchart}} and -#' \code{\link[corrplot]{corrplot}} for plotting methods used. -#' -#' \code{\link{fmSdDecomp}}, \code{\link{fmEsDecomp}}, -#' \code{\link{fmVaRDecomp}} for factor model risk measures. -#' -#' @examples -#' -#' # load data from the database -#' data(managers) -#' fit.macro <- fitTsfm(asset.names=colnames(managers[,(1:6)]), -#' factor.names=colnames(managers[,(7:8)]), -#' rf.name="US.3m.TR", data=managers) -#' -#' # group plot(default); select type from menu prompt -#' # menu is auto-looped to get multiple types of plots based on the same fit -#' # plot(fit.macro) -#' -#' # plot the factor betas of 1st 4 assets fitted above -#' # loop disabled to get one type of plot without interative menu -#' plot(fit.macro, max.show=4, which.plot.group=2, loop=FALSE) -#' -#' # plot factor model return correlation; angular order of the eigenvectors -#' plot(fit.macro, which.plot.group=7, loop=FALSE, -#' order="AOE", method="ellipse", tl.pos = "d") -#' -#' # histogram of residuals from an individual asset's factor model fit -#' plot(fit.macro, plot.single=TRUE, asset.name="HAM1", which.plot.single=8, -#' loop=FALSE) -#' -#' @importFrom PerformanceAnalytics chart.TimeSeries chart.ACFplus -#' chart.Histogram chart.QQPlot -#' @importFrom lattice barchart panel.barchart panel.grid -#' @importFrom corrplot corrplot -#' @importFrom strucchange efp -#' @importFrom robust lmRob -#' -#' @method plot tsfm -#' @export - -plot.tsfm <- function(x, which.plot.group=NULL, max.show=6, plot.single=FALSE, - asset.name, which.plot.single=NULL, colorset=(1:12), - legend.loc="topleft", las=1, VaR.method="historical", - loop=TRUE, ...) { - - if (plot.single==TRUE) { - - if (missing(asset.name) && length(x$asset.names)>1) { - stop("Missing input: 'asset.name' is required if plot.single is TRUE and - the factor model fits multiple assets.") - } else if (length(x$asset.names)==1) { - i <- x$asset.names[1] - } else { - i <- asset.name - } - # extract info from the fitTsfm object - plotData <- merge.xts(x$data[,i], fitted(x)[,i]) - colnames(plotData) <- c("Actual","Fitted") - Residuals <- residuals(x)[,i] - fit <- x$asset.fit[[i]] - - # plot selection - repeat { - if (is.null(which.plot.single)) { - which.plot.single <- - menu(c("Time series plot of actual and fitted asset returns", - "Time series plot of residuals with standard error bands", - "Time series plot of squared residuals", - "Time series plot of absolute residuals", - "SACF and PACF of residuals", - "SACF and PACF of squared residuals", - "SACF and PACF of absolute residuals", - "Histogram of residuals with normal curve overlayed", - "Normal qq-plot of residuals", - "CUSUM test-Recursive residuals", - "CUSUM test-OLS residuals", - "Recursive estimates (RE) test of OLS regression coefficients", - "Rolling estimates over a 24-period observation window"), - title="\nMake a plot selection (or 0 to exit):") - } - - par(las=las) # default horizontal axis labels - - switch(which.plot.single, - "1L" = { - ## time series plot of actual and fitted asset returns - chart.TimeSeries(plotData, main=paste("Returns:",i), - colorset=colorset, xlab="", - ylab="Actual and fitted asset returns", - legend.loc=legend.loc, pch=NULL, las=las, ...) - }, "2L" = { - ## time series plot of residuals with standard error bands - chart.TimeSeries(Residuals, main=paste("Residuals:",i), - colorset=colorset, xlab="", ylab="Residuals", - lwd=2, lty="solid", las=las, ...) - abline(h=1.96*x$resid.sd[i], lwd=2, lty="dotted", col="red") - abline(h=-1.96*x$resid.sd[i], lwd=2, lty="dotted", col="red") - legend(x=legend.loc, lty=c("solid","dotted"), - col=c(colorset[1],"red"), lwd=2, - legend=c("Residuals",expression("\u00b1 1.96"*sigma))) - }, "3L" = { - ## time series plot of squared residuals - chart.TimeSeries(Residuals^2, colorset=colorset, xlab="", - ylab=" Squared Residuals", - main=paste("Squared Residuals:",i), - legend.loc=legend.loc, pch=NULL, las=las, ...) - }, "4L" = { - ## time series plot of absolute residuals - chart.TimeSeries(abs(Residuals), colorset=colorset, xlab="", - ylab="Absolute Residuals", - main=paste("Absolute Residuals:",i), - legend.loc=legend.loc, pch=NULL, las=las, ...) - }, "5L" = { - ## SACF and PACF of residuals - chart.ACFplus(Residuals, col=colorset[1], - main=paste("SACF & PACF - Residuals:",i), ...) - }, "6L" = { - ## SACF and PACF of squared residuals - chart.ACFplus(Residuals^2, col=colorset[1], ..., - main=paste("SACF & PACF - Squared residuals:",i)) - }, "7L" = { - ## SACF and PACF of absolute residuals - chart.ACFplus(abs(Residuals), col=colorset[1], ..., - main=paste("SACF & PACF - Absolute Residuals:",i)) - }, "8L" = { - ## histogram of residuals with normal curve overlayed - methods <- c("add.density","add.normal","add.rug") - chart.Histogram(Residuals, xlab="Return residuals", - methods=methods, colorset=colorset, - main=paste("Histogram of Residuals:",i), ...) - }, "9L" = { - ## normal qq-plot of residuals - chart.QQPlot(Residuals, envelope=0.95, col=colorset, - main=paste("QQ-plot of Residuals:",i), ...) - legend(x=legend.loc, col="red", lty="dotted", lwd=1, - legend=c("0.95 confidence envelope")) - }, "10L" = { - ## Recursive CUSUM test - if (!x$fit.method=="OLS") { - stop("CUSUM analysis applicable only for 'OLS' fit.method.") - } - cusum.rec <- efp(formula(fit), type="Rec-CUSUM", data=fit$model) - plot(cusum.rec, main=paste("Recursive CUSUM test:",i), las=las, - col=colorset, ...) - }, "11L" = { - ## OLS-based CUSUM test - if (!x$fit.method=="OLS") { - stop("CUSUM analysis applicable only for 'OLS' fit.method.") - } - cusum.ols <- efp(formula(fit), type="OLS-CUSUM", data=fit$model) - plot(cusum.ols, main=paste("OLS-based CUSUM test:",i), las=las, - col=colorset, ...) - }, "12L" = { - ## Recursive estimates (RE) test of OLS regression coefficients - if (!x$fit.method=="OLS") { - stop("CUSUM analysis applicable only for 'OLS' fit.method.") - } - cusum.est <- efp(formula(fit), type="RE", data=fit$model) - plot(cusum.est, functional=NULL, col=colorset, las=0, - main=paste("RE test (Recursive estimates test):",i), ...) - }, "13L" = { - ## Rolling estimates over 24-period observation window - if (x$fit.method=="OLS") { - rollReg <- function(data.z, formula) { - coef(lm(formula, data=as.data.frame(data.z))) - } - reg.z <- zoo(fit$model, as.Date(rownames(fit$model))) - rollReg.z <- rollapply(reg.z, FUN=rollReg, formula(fit), - width=24, by.column=FALSE, align="right") - } else if (x$fit.method=="DLS") { - # get decay factor - if (as.character(x$call["decay"])=="NULL") { - decay <- 0.95 # default value for the decay factor - } else { - decay <- as.numeric(as.character(x$call["decay"])) - } - # calculate exp. decaying weights for 24-period window - w <- decay^seq(23,0,-1) - w <- w/sum(w) # weights sum to unity - rollReg.w <- function(data.z, formula, w) { - coef(lm(formula, weights=w, data=as.data.frame(data.z))) - } - reg.z <- zoo(fit$model[-length(fit$model)], - as.Date(rownames(fit$model))) - rollReg.z <- rollapply(reg.z, FUN=rollReg.w, formula(fit), w, - width=24, by.column=FALSE, align="right") - } else if (x$fit.method=="Robust") { - rollReg.Rob <- function(data.z, formula) { - coef(lmRob(formula=formula, data=as.data.frame(data.z))) - } - reg.z <- zoo(fit$model, as.Date(rownames(fit$model))) - rollReg.z <- rollapply(reg.z, width=24, FUN=rollReg.Rob, - formula(fit), by.column=FALSE, - align="right") - } else if (is.null(x$fit.method)) { - stop("Rolling estimates is not available for 'lars' fits.") - } - par(las=0) - plot(rollReg.z, ..., las=las, - main=paste("Rolling estimates (24-period obs window):",i)) - par(las=las) - }, - invisible() - ) - # repeat menu if user didn't choose to exit from the plot options - if (which.plot.single==0 || loop==FALSE) {break} - else {which.plot.single=NULL} - } - } else { # start of group asset plots - - # plot selection - repeat { - if (is.null(which.plot.group)) { - which.plot.group <- - menu(c("Factor model coefficients: Alpha", - "Factor model coefficients: Betas", - "Actual and Fitted asset returns", - "R-squared", - "Residual Volatility", - "Factor Model Residual Correlation", - "Factor Model Return Correlation", - "Factor Contribution to SD", - "Factor Contribution to ES", - "Factor Contribution to VaR"), - title="\nMake a plot selection (or 0 to exit):") - } - - par(las=las) # default horizontal axis labels - - switch(which.plot.group, - "1L" = { - ## Factor model coefficients: Alpha - barplot(coef(x)[,1], main="Factor model Alpha (Intercept)", - names.arg=rownames(coef(x)), col="darkblue", las=las, - horiz=TRUE, ...) - abline(v=0, lwd=1, lty=1, col=1) - }, - "2L" = { - ## Factor model coefficients: Betas - k <- ncol(coef(x))-1 - if (k > max.show) { - cat(paste("Displaying only the first", max.show,"factor betas, as the number of factors > 'max.show' =", max.show)) - k <- max.show - } - par(mfrow=c(ceiling(k/2),2)) - for (i in 2:(k+1)) { - main=paste(colnames(coef(x))[i], "factor Betas") - barplot(coef(x)[,i], main=main, names.arg=rownames(coef(x)), - col="darkblue", las=las, horiz=TRUE, ...) - abline(v=0, lwd=1, lty=1, col=1) - } - par(mfrow=c(1,1)) - }, - "3L" = { - ## Actual and Fitted asset returns - n <- length(x$asset.names) - if (n > max.show) { - cat(paste("Displaying only the first", max.show, "assets, since the number of assets > 'max.show'")) - n <- max.show - } - par(mfrow=c(ceiling(n/2),2)) - for (i in 1:n) { - plotData <- merge.xts(x$data[,i], fitted(x)[,i]) - colnames(plotData) <- c("Actual","Fitted") - main <- paste("Factor model asset returns:", x$asset.names[i]) - chart.TimeSeries(plotData, colorset=colorset, main=main, - xlab="", ylab="Actual and fitted values", - legend.loc=legend.loc, pch=NULL, las=las,...) - } - par(mfrow=c(1,1)) - }, - "4L" ={ - ## R-squared - plot( - barchart(x$r2, main="R-squared values", xlab="", - col="darkblue", ...) - ) - }, - "5L" = { - ## Residual Volatility - plot( - barchart(x$resid.sd, main="Residual volatility", xlab="", - col="darkblue", ...) - ) - }, - "6L" = { - ## Factor Model Residual Correlation - cor.resid <- cor(residuals(x), use="pairwise.complete.obs") - corrplot(cor.resid, ...) - # mtext("pairwise complete obs", line=0.5) - }, - "7L" = { - ## Factor Model Return Correlation - cor.fm <- cov2cor(fmCov(x)) - corrplot(cor.fm, ...) - # mtext("pairwise complete obs", line=0.5) - }, - "8L" = { - ## Factor Percentage Contribution to SD - pcSd.fm <- fmSdDecomp(x)$pcSd - plot( - barchart(pcSd.fm, main="Factor % Contribution to SD", xlab="", - auto.key=list(space="bottom",columns=3, - points=FALSE,rectangles=TRUE), - par.settings=list(superpose.polygon=list(col=colorset)), - panel=function(...){panel.grid(h=0, v=-1); - panel.barchart(...)}, ...) - ) - }, - "9L"={ - ## Factor Percentage Contribution to ES - pcES.fm <- fmEsDecomp(x, method=VaR.method)$pcES - plot( - barchart(pcES.fm, main="Factor % Contribution to ES", xlab="", - auto.key=list(space="bottom",columns=3, - points=FALSE,rectangles=TRUE), - par.settings=list(superpose.polygon=list(col=colorset)), - panel=function(...){panel.grid(h=0, v=-1); - panel.barchart(...)}, ...) - ) - }, - "10L" ={ - ## Factor Percentage Contribution to VaR - pcVaR.fm <- fmVaRDecomp(x, method=VaR.method)$pcVaR - plot( - barchart(pcVaR.fm, main="Factor % Contribution to VaR", - xlab="", auto.key=list(space="bottom",columns=3, - points=FALSE,rectangles=TRUE), - par.settings=list(superpose.polygon=list(col=colorset)), - panel=function(...){panel.grid(h=0, v=-1); - panel.barchart(...)}, ...) - ) - }, - invisible() - ) - # repeat menu if user didn't choose to exit from the plot options - if (which.plot.group==0 || loop==FALSE) {break} - else {which.plot.group=NULL} - } - } # end of group plots -} +#' @title Plots from a fitted time series factor model +#' +#' @description Generic \code{plot} method for object of class \code{tsfm}. +#' Plots chosen characteristic(s) for one or more assets. +#' +#' @details +#' +#' The function can be used for group plots and individual plots. User can +#' select the type of plot either from the menu prompt (default) or directly +#' via argument \code{which}. +#' +#' In case multiple plots are needed, the menu is repeated after each plot +#' (enter 0 to exit). User can also input a numeric vector of plot options via +#' \code{which}. +#' +#' For group plots (the default), the first \code{max.show} assets are plotted. +#' +#' Setting \code{plot.single=TRUE} enables individual plots. If there is more +#' than one asset fit by \code{x}, \code{asset.name} should be specified. +#' However, if the \code{tsfm} object \code{x} only contains one asset?s factor +#' model fit, plot.tsfm can infer \code{asset.name} without user input. +#' +#' CUSUM plots (individual asset plot options 10, 11 and 12) are applicable +#' only for \code{fit.method="OLS"}. +#' +#' Rolling estimates (individual asset plot option 13) is not applicable for +#' \code{variable.slection="lars"}. +#' +#' @param x an object of class \code{tsfm} produced by \code{fitTsfm}. +#' @param which a number to indicate the type of plot. If a subset of the plots +#' is required, specify a subset of the numbers 1:10 for group plots and 1:16 +#' for individual plots. If \code{which=NULL} (default), the following menu +#' appears: \cr \cr +#' For plots of a group of assets: \cr +#' 1 = Factor model coefficients: Alpha, \cr +#' 2 = Factor model coefficients: Betas, \cr +#' 3 = Actual and Fitted asset returns, \cr +#' 4 = R-squared, \cr +#' 5 = Residual Volatility,\cr +#' 6 = Factor Model Residual Correlation \cr +#' 7 = Factor Model Correlation,\cr +#' 8 = Factor Contribution to SD,\cr +#' 9 = Factor Contribution to ES,\cr +#' 10 = Factor Contribution to VaR \cr \cr +#' For individual asset plots:\cr +#' 1 = Actual and fitted returns,\cr +#' 2 = Residuals and fitted returns, \cr +#' 3 = Scale-Location plot, \cr +#' 4 = Residuals with standard error bands, \cr +#' 5 = Time series of squared residuals, \cr +#' 6 = Time series of absolute residuals,\cr +#' 7 = SACF and PACF of residuals,\cr +#' 8 = SACF and PACF of squared residuals,\cr +#' 9 = SACF and PACF of absolute residuals,\cr +#' 10 = Density estimate of residuals, \cr +#' 11 = Histogram of residuals with normal curve overlayed,\cr +#' 12 = Normal QQ-plot of residuals,\cr +#' 13 = CUSUM test-Recursive residuals,\cr +#' 14 = CUSUM test-OLS residuals,\cr +#' 15 = Recursive estimates (RE) test of OLS regression coefficients,\cr +#' 16 = Rolling estimates over a 24-period observation window +#' @param max.show maximum number of assets in a given plot. Default is 6. +#' @param plot.single logical; If \code{TRUE} plots the characteristics of an +#' individual asset's factor model. The type of plot is given by +#' \code{which}. Default is \code{FALSE}. +#' @param asset.name name of the individual asset to be plotted. Is necessary +#' if \code{x} contains multiple asset fits and \code{plot.single=TRUE}. +#' @param colorset color palette to use for all the plots. Default is +#' \code{c(1:12)}. The 1st element will be used for individual time series +#' plots or the 1st series plotted, the 2nd element for the 2nd object in the +#' plot and so on. +#' @param legend.loc places a legend into one of nine locations on the chart: +#' "bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", +#' "right", or "center". Default is "bottomright". Use \code{legend.loc=NULL} +#' to suppress the legend. +#' @param las one of {0, 1, 2, 3} to set the direction of axis labels, same as +#' in \code{plot}. Default here is 1. +#' @param VaR.method a method for computing VaR; one of "modified", "gaussian", +#' "historical" or "kernel". VaR is computed using +#' \code{\link[PerformanceAnalytics]{VaR}}. Default is "historical". +#' @param ... further arguments to be passed to other plotting functions. +#' +#' @author Eric Zivot, Sangeetha Srinivasan and Yi-An Chen +#' +#' @seealso \code{\link{fitTsfm}} and \code{\link{summary.tsfm}} for details +#' about the time series factor model fit, extractor functions and summary +#' statistics. +#' +#' \code{\link[strucchange]{efp}} for CUSUM tests. +#' +#' \code{\link[xts]{plot.xts}}, [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3613 From noreply at r-forge.r-project.org Mon Mar 16 05:25:24 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 16 Mar 2015 05:25:24 +0100 (CET) Subject: [Returnanalytics-commits] r3614 - in pkg/FactorAnalytics: . R man Message-ID: <20150316042525.08FA6185493@r-forge.r-project.org> Author: chenyian Date: 2015-03-16 05:25:23 +0100 (Mon, 16 Mar 2015) New Revision: 3614 Modified: pkg/FactorAnalytics/DESCRIPTION pkg/FactorAnalytics/R/fitTsfm.R pkg/FactorAnalytics/R/fitTsfmMT.r pkg/FactorAnalytics/R/fitTsfmUpDn.r pkg/FactorAnalytics/R/plot.tsfmUpDn.r pkg/FactorAnalytics/R/print.tsfm.r pkg/FactorAnalytics/man/CornishFisher.Rd pkg/FactorAnalytics/man/fitSfm.Rd pkg/FactorAnalytics/man/fitTsfm.Rd pkg/FactorAnalytics/man/fitTsfm.control.Rd pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd pkg/FactorAnalytics/man/fitTsfmMT.Rd pkg/FactorAnalytics/man/fitTsfmUpDn.Rd pkg/FactorAnalytics/man/fmCov.Rd pkg/FactorAnalytics/man/fmEsDecomp.Rd pkg/FactorAnalytics/man/fmSdDecomp.Rd pkg/FactorAnalytics/man/fmVaRDecomp.Rd pkg/FactorAnalytics/man/paFm.Rd pkg/FactorAnalytics/man/plot.pafm.Rd pkg/FactorAnalytics/man/plot.sfm.Rd pkg/FactorAnalytics/man/plot.tsfm.Rd pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd pkg/FactorAnalytics/man/predict.sfm.Rd pkg/FactorAnalytics/man/predict.tsfm.Rd pkg/FactorAnalytics/man/predict.tsfmUpDn.Rd pkg/FactorAnalytics/man/print.pafm.Rd pkg/FactorAnalytics/man/print.sfm.Rd pkg/FactorAnalytics/man/print.tsfm.Rd pkg/FactorAnalytics/man/print.tsfmUpDn.Rd pkg/FactorAnalytics/man/summary.pafm.Rd pkg/FactorAnalytics/man/summary.sfm.Rd pkg/FactorAnalytics/man/summary.tsfm.Rd pkg/FactorAnalytics/man/summary.tsfmUpDn.Rd Log: version 2.0.13. 1. move the market timing chunk of codes from fitTsfm.R to fitTsfmMT.r Modified: pkg/FactorAnalytics/DESCRIPTION =================================================================== --- pkg/FactorAnalytics/DESCRIPTION 2015-03-15 19:34:35 UTC (rev 3613) +++ pkg/FactorAnalytics/DESCRIPTION 2015-03-16 04:25:23 UTC (rev 3614) @@ -1,36 +1,36 @@ -Package: factorAnalytics -Type: Package -Title: Factor Analytics -Version: 2.0.12 -Date: 2015-03-15 -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.13 +Date: 2015-03-15 +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-03-15 19:34:35 UTC (rev 3613) +++ pkg/FactorAnalytics/R/fitTsfm.R 2015-03-16 04:25:23 UTC (rev 3614) @@ -1,569 +1,549 @@ -#' @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. A wrapper function -#' \code{\link{fitTsfmMT}} is built based on this functionality. Please refer to -#' \code{fitTsfmMT} for detail. -#' -#' \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=1) -#' # group plot; type selected from menu prompt; auto-looped for multiple plots -#' # plot(fit) -#' -#' -#' # example using "subsets" variable selection -#' fit.sub <- fitTsfm(asset.names=colnames(managers[,(1:6)]), -#' 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)))) - } - - # opt add mkt-timing factors: down.market=max(0,Rf-Rm), market.sqd=(Rm-Rf)^2 - if("HM" %in% mkt.timing) { - 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" - 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. A wrapper function +#' \code{\link{fitTsfmMT}} is built based on this functionality. Please refer to +#' \code{fitTsfmMT} for detail. +#' +#' \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 eturns. +#' @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.} [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3614 From noreply at r-forge.r-project.org Mon Mar 16 06:15:22 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 16 Mar 2015 06:15:22 +0100 (CET) Subject: [Returnanalytics-commits] r3615 - in pkg/FactorAnalytics: . R man Message-ID: <20150316051522.D0AA518541D@r-forge.r-project.org> Author: pragnya Date: 2015-03-16 06:15:22 +0100 (Mon, 16 Mar 2015) New Revision: 3615 Modified: pkg/FactorAnalytics/DESCRIPTION pkg/FactorAnalytics/R/fitTsfm.R pkg/FactorAnalytics/R/fitTsfm.control.R pkg/FactorAnalytics/man/fitTsfm.Rd pkg/FactorAnalytics/man/fitTsfm.control.Rd Log: Added control parameter efficiency for lm.Rob Modified: pkg/FactorAnalytics/DESCRIPTION =================================================================== --- pkg/FactorAnalytics/DESCRIPTION 2015-03-16 04:25:23 UTC (rev 3614) +++ pkg/FactorAnalytics/DESCRIPTION 2015-03-16 05:15:22 UTC (rev 3615) @@ -1,36 +1,36 @@ -Package: factorAnalytics -Type: Package -Title: Factor Analytics -Version: 2.0.13 -Date: 2015-03-15 -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.14 +Date: 2015-03-15 +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-03-16 04:25:23 UTC (rev 3614) +++ pkg/FactorAnalytics/R/fitTsfm.R 2015-03-16 05:15:22 UTC (rev 3615) @@ -1,549 +1,546 @@ -#' @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. A wrapper function -#' \code{\link{fitTsfmMT}} is built based on this functionality. Please refer to -#' \code{fitTsfmMT} for detail. -#' -#' \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 eturns. -#' @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 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=1) -#' # group plot; type selected from menu prompt; auto-looped for multiple plots -#' # plot(fit) -#' -#' -#' # example using "subsets" variable selection -#' fit.sub <- fitTsfm(asset.names=colnames(managers[,(1:6)]), -#' 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") - , 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 - } - - # 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)))) - } - - - - # 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. +#' +#' Argument \code{mkt.name} can be used to add market-timing factors to any of +#' the above methods. Please refer to \code{\link{fitTsfmMT}}, a wrapper to +#' \code{fitTsfm} for details. +#' +#' \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 returns. 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 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 [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3615 From noreply at r-forge.r-project.org Mon Mar 16 17:15:01 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 16 Mar 2015 17:15:01 +0100 (CET) Subject: [Returnanalytics-commits] r3616 - in pkg/FactorAnalytics: R man Message-ID: <20150316161501.76946186B46@r-forge.r-project.org> Author: chenyian Date: 2015-03-16 17:15:01 +0100 (Mon, 16 Mar 2015) New Revision: 3616 Modified: pkg/FactorAnalytics/R/plot.tsfmUpDn.r pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd Log: Add legend and line color and line type option in plot.tsfmUpDn.r Modified: pkg/FactorAnalytics/R/plot.tsfmUpDn.r =================================================================== --- pkg/FactorAnalytics/R/plot.tsfmUpDn.r 2015-03-16 05:15:22 UTC (rev 3615) +++ pkg/FactorAnalytics/R/plot.tsfmUpDn.r 2015-03-16 16:15:01 UTC (rev 3616) @@ -14,6 +14,10 @@ #' to provide the name of market returns. #' @param assets.name The name of the asset used in \code{fitTsfmUpDn}. It supports one #' asset name at once. +#' @param line.color The color of fitted line. The default is \code{"blue"}. +#' @param line.type The type of fitted line. The default is \code{"dotted"}. +#' @param add.legend Alogic flag to add legend. The default is \code{TRUE} +#' @param legend.loc The default is \code{"topleft"}. #' @param ... Other arguments can be used in \code{plot}. #' @author Yi-An Chen #' @@ -34,7 +38,8 @@ #' @export -plot.tsfmUpDn <- function(object,mkt.name,assets.name,...) { +plot.tsfmUpDn <- function(object,mkt.name,assets.name,line.color="blue",line.type="dotted", + add.legend=TRUE,legend.loc="topleft",...) { if (is.null(mkt.name)){ stop("Missing argument: mkt.name has to be specified for plot method.") @@ -59,9 +64,13 @@ 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="blue") - lines(coredata(plotDataDn$MktDn),coredata(plotDataDn$FittedDn),col="blue") + lines(coredata(plotDataUp$MktUp),coredata(plotDataUp$FittedUp),col=line.color,lty=line.type) + lines(coredata(plotDataDn$MktDn),coredata(plotDataDn$FittedDn),col=line.color,lty=line.type) abline(h=0) + if (add.legend){ + legend(legend.loc,legend=c("Actual","Fitted"),pch=c(1,NA),lty=c(NA,line.type), + col=c("black",line.color),...) + } } \ No newline at end of file Modified: pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd =================================================================== --- pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd 2015-03-16 05:15:22 UTC (rev 3615) +++ pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd 2015-03-16 16:15:01 UTC (rev 3616) @@ -4,7 +4,8 @@ \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, ...) +\method{plot}{tsfmUpDn}(object, mkt.name, assets.name, line.color = "blue", + line.type = "dotted", add.legend = TRUE, legend.loc = "topleft", ...) } \arguments{ \item{object}{an object of class \code{tsfmUpDn} produced by \code{fitTsfmUpDn}.} @@ -15,6 +16,14 @@ \item{assets.name}{The name of the asset used in \code{fitTsfmUpDn}. It supports one asset name at once.} +\item{line.color}{The color of fitted line. The default is \code{"blue"}.} + +\item{line.type}{The type of fitted line. The default is \code{"dotted"}.} + +\item{add.legend}{Alogic flag to add legend. The default is \code{TRUE}} + +\item{legend.loc}{The default is \code{"topleft"}.} + \item{...}{Other arguments can be used in \code{plot}.} } \description{ From noreply at r-forge.r-project.org Mon Mar 16 21:41:50 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 16 Mar 2015 21:41:50 +0100 (CET) Subject: [Returnanalytics-commits] r3617 - in pkg/FactorAnalytics: R man Message-ID: <20150316204150.F3192185509@r-forge.r-project.org> Author: pragnya Date: 2015-03-16 21:41:50 +0100 (Mon, 16 Mar 2015) New Revision: 3617 Modified: pkg/FactorAnalytics/R/fitTsfm.R pkg/FactorAnalytics/R/summary.tsfm.r pkg/FactorAnalytics/man/fitTsfm.Rd pkg/FactorAnalytics/man/summary.tsfm.Rd Log: Added option to trim summary; Add mkt.name to output tsfm object Modified: pkg/FactorAnalytics/R/fitTsfm.R =================================================================== --- pkg/FactorAnalytics/R/fitTsfm.R 2015-03-16 16:15:01 UTC (rev 3616) +++ pkg/FactorAnalytics/R/fitTsfm.R 2015-03-16 20:41:50 UTC (rev 3617) @@ -95,6 +95,7 @@ #' \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{mkt.name}{mkt.name 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 @@ -226,6 +227,8 @@ # 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) + mkt.name <- gsub(" ",".", mkt.name, fixed=TRUE) + rf.name <- gsub(" ",".", rf.name, fixed=TRUE) # Selects regression procedure based on specified variable.selection method. # Each method returns a list of fitted factor models for each asset. @@ -243,7 +246,7 @@ 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, + factor.names=factor.names, mkt.name=mkt.name, fit.method=NULL, variable.selection=variable.selection) result <- c(result.lars, input) class(result) <- "tsfm" @@ -268,7 +271,8 @@ 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) + mkt.name=mkt.name, fit.method=fit.method, + variable.selection=variable.selection) class(result) <- "tsfm" return(result) } Modified: pkg/FactorAnalytics/R/summary.tsfm.r =================================================================== --- pkg/FactorAnalytics/R/summary.tsfm.r 2015-03-16 16:15:01 UTC (rev 3616) +++ pkg/FactorAnalytics/R/summary.tsfm.r 2015-03-16 20:41:50 UTC (rev 3617) @@ -1,134 +1,147 @@ -#' @title Summarizing a fitted time series factor model -#' -#' @description \code{summary} method for object of class \code{tsfm}. -#' Returned object is of class {summary.tsfm}. -#' -#' @details The default \code{summary} method for a fitted \code{lm} object -#' computes the standard errors and t-statistics under the assumption of -#' homoskedasticty. Argument \code{se.type} gives the option to compute -#' heteroskedasticity-consistent (HC) or -#' heteroskedasticity-autocorrelation-consistent (HAC) standard errors and -#' t-statistics using \code{\link[lmtest]{coeftest}}. This option is meaningful -#' only if \code{fit.method = "OLS" or "DLS"}. -#' -#' Standard errors are currently not available for -#' \code{variable.selection="lars"} as there seems to be no consensus on a -#' statistically valid method of calculating standard errors for the lasso -#' predictions. -#' -#' @param object an object of class \code{tsfm} returned by \code{fitTsfm}. -#' @param se.type one of "Default", "HC" or "HAC"; option for computing -#' HC/HAC standard errors and t-statistics. Default is "Default". -#' @param x an object of class \code{summary.tsfm}. -#' @param digits number of significants digits to use when printing. -#' Default is 3. -#' @param ... futher arguments passed to or from other methods. -#' -#' @return Returns an object of class \code{summary.tsfm}. -#' The print method for class \code{summary.tsfm} outputs the call, -#' coefficients (with standard errors and t-statistics), r-squared and -#' residual volatilty (under the homoskedasticity assumption) for all assets. -#' -#' Object of class \code{summary.tsfm} is a list of length N + 2 containing: -#' \item{call}{the function call to \code{fitTsfm}} -#' \item{se.type}{standard error type as input} -#' \item{sum.list}{list of summaries of the N fit objects (of class \code{lm}, -#' \code{lmRob} or \code{lars}) for each asset in the factor model.} -#' -#' @author Sangeetha Srinivasan & Yi-An Chen. -#' -#' @seealso \code{\link{fitTsfm}}, \code{\link[stats]{summary.lm}} -#' -#' @examples -#' data(managers) -#' fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), -#' factor.names=colnames(managers[,7:9]), -#' data=managers) -#' -#' # summary of factor model fit for all assets -#' summary(fit, "HAC") -#' -#' # summary of lm fit for a single asset -#' summary(fit$asset.fit[[1]]) -#' -#' @importFrom lmtest coeftest.default -#' @importFrom sandwich vcovHC.default vcovHAC.default -#' -#' @method summary tsfm -#' @export - -summary.tsfm <- function(object, se.type=c("Default","HC","HAC"), ...){ - - # check input object validity - if (!inherits(object, "tsfm")) { - stop("Invalid 'tsfm' object") - } - - #set default for se.type - se.type = se.type[1] - - # note: fit.method=NULL for "lars" objects - if (object$fit.method=="Robust" && se.type!="Default") { - stop("Invalid argument: HC/HAC standard errors are applicable only if - fit.method = 'OLS' or 'DLS'") - } - - # extract summary.lm objects for each asset - sum.list <- lapply(object$asset.fit, summary) - - # convert to HC/HAC standard errors and t-stats if specified - # extract coefficients separately for "lars" variable.selection method - for (i in object$asset.names) { - if (se.type=="HC") { - sum.list[[i]]$coefficients <- coeftest.default(object$asset.fit[[i]], - vcov.=vcovHC.default)[,1:4] - } else if (se.type=="HAC") { - sum.list[[i]]$coefficients <- coeftest.default(object$asset.fit[[i]], - vcov.=vcovHAC.default)[,1:4] - } - } - - if (object$variable.selection=="lars") { - sum.list <- list() - for (i in object$asset.names) { - sum.list[[i]]$coefficients <- as.matrix(c(object$alpha[i], object$beta[i,])) - rownames(sum.list[[i]]$coefficients)[1]="(Intercept)" - colnames(sum.list[[i]]$coefficients)[1]="Estimate" - sum.list[[i]]$r.squared <- as.numeric(object$r2[i]) - sum.list[[i]]$sigma <- as.numeric(object$resid.sd[i]) - } - } - - # include the call and se.type to fitTsfm - sum <- list(call=object$call, se.type=se.type, sum.list=sum.list) - class(sum) <- "summary.tsfm" - return(sum) -} - - -#' @rdname summary.tsfm -#' @method print summary.tsfm -#' @export - -print.summary.tsfm <- function(x, digits=3, ...) { - if(!is.null(cl <- x$call)) { - cat("\nCall:\n") - dput(cl) - } - cat("\nFactor Model Coefficients:\n", sep="") - n <- length(x$sum.list) - for (i in 1:n) { - options(digits = digits) - table.coef <- (x$sum.list)[[i]]$coefficients - if (dim(table.coef)[2] > 1) { - cat("\nAsset", i, ": ", names(x$sum.list[i]), "\n(", x$se.type, - " Standard Errors & T-stats)\n\n", sep="") - } else { - cat("\nAsset", i, ": ", names(x$sum.list[i]), "\n\n", sep="") - } - r2 <- x$sum.list[[i]]$r.squared - sigma <- x$sum.list[[i]]$sigma - printCoefmat(table.coef, digits=digits, ...) - cat("\nR-squared: ", r2,", Residual Volatility: ", sigma,"\n", sep="") - } -} +#' @title Summarizing a fitted time series factor model +#' +#' @description \code{summary} method for object of class \code{tsfm}. +#' Returned object is of class {summary.tsfm}. +#' +#' @details The default \code{summary} method for a fitted \code{lm} object +#' computes the standard errors and t-statistics under the assumption of +#' homoskedasticty. Argument \code{se.type} gives the option to compute +#' heteroskedasticity-consistent (HC) or +#' heteroskedasticity-autocorrelation-consistent (HAC) standard errors and +#' t-statistics using \code{\link[lmtest]{coeftest}}. This option is meaningful +#' only if \code{fit.method = "OLS" or "DLS"}. +#' +#' Standard errors are currently not available for +#' \code{variable.selection="lars"} as there seems to be no consensus on a +#' statistically valid method of calculating standard errors for the lasso +#' predictions. +#' +#' @param object an object of class \code{tsfm} returned by \code{fitTsfm}. +#' @param se.type one of "Default", "HC" or "HAC"; option for computing +#' HC/HAC standard errors and t-statistics. Default is "Default". +#' @param x an object of class \code{summary.tsfm}. +#' @param digits number of significants digits to use when printing. +#' Default is 3. +#' @param trim option to supress labels and legend in the summary. When +#' \code{TRUE}, only the coefficient matrx with standard eroors is printed. +#' Default is \code{FALSE}. +#' @param ... futher arguments passed to or from other methods. +#' +#' @return Returns an object of class \code{summary.tsfm}. +#' The print method for class \code{summary.tsfm} outputs the call, +#' coefficients (with standard errors and t-statistics), r-squared and +#' residual volatilty (under the homoskedasticity assumption) for all assets. +#' +#' Object of class \code{summary.tsfm} is a list of length N + 2 containing: +#' \item{call}{the function call to \code{fitTsfm}} +#' \item{se.type}{standard error type as input} +#' \item{sum.list}{list of summaries of the N fit objects (of class \code{lm}, +#' \code{lmRob} or \code{lars}) for each asset in the factor model.} +#' +#' @author Sangeetha Srinivasan & Yi-An Chen. +#' +#' @seealso \code{\link{fitTsfm}}, \code{\link[stats]{summary.lm}} +#' +#' @examples +#' data(managers) +#' fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), +#' factor.names=colnames(managers[,7:9]), +#' data=managers) +#' +#' # summary of factor model fit for all assets +#' summary(fit, "HAC") +#' +#' # summary of lm fit for a single asset +#' summary(fit$asset.fit[[1]]) +#' +#' @importFrom lmtest coeftest.default +#' @importFrom sandwich vcovHC.default vcovHAC.default +#' +#' @method summary tsfm +#' @export + +summary.tsfm <- function(object, se.type=c("Default","HC","HAC"), ...){ + + # check input object validity + if (!inherits(object, "tsfm")) { + stop("Invalid 'tsfm' object") + } + + #set default for se.type + se.type = se.type[1] + + # note: fit.method=NULL for "lars" objects + if (object$fit.method=="Robust" && se.type!="Default") { + stop("Invalid argument: HC/HAC standard errors are applicable only if + fit.method = 'OLS' or 'DLS'") + } + + # extract summary.lm objects for each asset + sum.list <- lapply(object$asset.fit, summary) + + # convert to HC/HAC standard errors and t-stats if specified + # extract coefficients separately for "lars" variable.selection method + for (i in object$asset.names) { + if (se.type=="HC") { + sum.list[[i]]$coefficients <- coeftest.default(object$asset.fit[[i]], + vcov.=vcovHC.default)[,1:4] + } else if (se.type=="HAC") { + sum.list[[i]]$coefficients <- coeftest.default(object$asset.fit[[i]], + vcov.=vcovHAC.default)[,1:4] + } + } + + if (object$variable.selection=="lars") { + sum.list <- list() + for (i in object$asset.names) { + sum.list[[i]]$coefficients <- as.matrix(c(object$alpha[i], object$beta[i,])) + rownames(sum.list[[i]]$coefficients)[1]="(Intercept)" + colnames(sum.list[[i]]$coefficients)[1]="Estimate" + sum.list[[i]]$r.squared <- as.numeric(object$r2[i]) + sum.list[[i]]$sigma <- as.numeric(object$resid.sd[i]) + } + } + + # include the call and se.type to fitTsfm + sum <- list(call=object$call, se.type=se.type, sum.list=sum.list) + class(sum) <- "summary.tsfm" + return(sum) +} + + +#' @rdname summary.tsfm +#' @method print summary.tsfm +#' @export + +print.summary.tsfm <- function(x, digits=3, trim=FALSE, ...) { + n <- length(x$sum.list) + if (trim==FALSE) { + if(!is.null(cl <- x$call)) { + cat("\nCall:\n") + dput(cl) + } + cat("\nFactor Model Coefficients:\n", sep="") + for (i in 1:n) { + options(digits = digits) + table.coef <- (x$sum.list)[[i]]$coefficients + if (dim(table.coef)[2] > 1) { + cat("\nAsset", i, ": ", names(x$sum.list[i]), "\n(", x$se.type, + " Standard Errors & T-stats)\n\n", sep="") + } else { + cat("\nAsset", i, ": ", names(x$sum.list[i]), "\n\n", sep="") + } + r2 <- x$sum.list[[i]]$r.squared + sigma <- x$sum.list[[i]]$sigma + printCoefmat(table.coef, digits=digits, ...) + cat("\nR-squared: ", r2,", Residual Volatility: ", sigma,"\n", sep="") + } + } else { + for (i in 1:n) { + options(digits = digits) + table.coef <- (x$sum.list)[[i]]$coefficients + cat(names(x$sum.list[i]), "\n") + printCoefmat(table.coef, digits=digits, signif.legend=FALSE, ...) + cat("\n") + } + } +} Modified: pkg/FactorAnalytics/man/fitTsfm.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfm.Rd 2015-03-16 16:15:01 UTC (rev 3616) +++ pkg/FactorAnalytics/man/fitTsfm.Rd 2015-03-16 20:41:50 UTC (rev 3617) @@ -74,6 +74,7 @@ \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{mkt.name}{mkt.name 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 Modified: pkg/FactorAnalytics/man/summary.tsfm.Rd =================================================================== --- pkg/FactorAnalytics/man/summary.tsfm.Rd 2015-03-16 16:15:01 UTC (rev 3616) +++ pkg/FactorAnalytics/man/summary.tsfm.Rd 2015-03-16 20:41:50 UTC (rev 3617) @@ -1,73 +1,76 @@ -% Generated by roxygen2 (4.1.0): do not edit by hand -% Please edit documentation in R/summary.tsfm.r -\name{summary.tsfm} -\alias{print.summary.tsfm} -\alias{summary.tsfm} -\title{Summarizing a fitted time series factor model} -\usage{ -\method{summary}{tsfm}(object, se.type = c("Default", "HC", "HAC"), ...) - -\method{print}{summary.tsfm}(x, digits = 3, ...) -} -\arguments{ -\item{object}{an object of class \code{tsfm} returned by \code{fitTsfm}.} - -\item{se.type}{one of "Default", "HC" or "HAC"; option for computing -HC/HAC standard errors and t-statistics. Default is "Default".} - -\item{...}{futher arguments passed to or from other methods.} - -\item{x}{an object of class \code{summary.tsfm}.} - -\item{digits}{number of significants digits to use when printing. -Default is 3.} -} -\value{ -Returns an object of class \code{summary.tsfm}. -The print method for class \code{summary.tsfm} outputs the call, -coefficients (with standard errors and t-statistics), r-squared and -residual volatilty (under the homoskedasticity assumption) for all assets. - -Object of class \code{summary.tsfm} is a list of length N + 2 containing: -\item{call}{the function call to \code{fitTsfm}} -\item{se.type}{standard error type as input} -\item{sum.list}{list of summaries of the N fit objects (of class \code{lm}, -\code{lmRob} or \code{lars}) for each asset in the factor model.} -} -\description{ -\code{summary} method for object of class \code{tsfm}. -Returned object is of class {summary.tsfm}. -} -\details{ -The default \code{summary} method for a fitted \code{lm} object -computes the standard errors and t-statistics under the assumption of -homoskedasticty. Argument \code{se.type} gives the option to compute -heteroskedasticity-consistent (HC) or -heteroskedasticity-autocorrelation-consistent (HAC) standard errors and -t-statistics using \code{\link[lmtest]{coeftest}}. This option is meaningful -only if \code{fit.method = "OLS" or "DLS"}. - -Standard errors are currently not available for -\code{variable.selection="lars"} as there seems to be no consensus on a -statistically valid method of calculating standard errors for the lasso -predictions. -} -\examples{ -data(managers) -fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), - factor.names=colnames(managers[,7:9]), - data=managers) - -# summary of factor model fit for all assets -summary(fit, "HAC") - -# summary of lm fit for a single asset -summary(fit$asset.fit[[1]]) -} -\author{ -Sangeetha Srinivasan & Yi-An Chen. -} -\seealso{ -\code{\link{fitTsfm}}, \code{\link[stats]{summary.lm}} -} - +% Generated by roxygen2 (4.0.2): do not edit by hand +\name{summary.tsfm} +\alias{print.summary.tsfm} +\alias{summary.tsfm} +\title{Summarizing a fitted time series factor model} +\usage{ +\method{summary}{tsfm}(object, se.type = c("Default", "HC", "HAC"), ...) + +\method{print}{summary.tsfm}(x, digits = 3, trim = FALSE, ...) +} +\arguments{ +\item{object}{an object of class \code{tsfm} returned by \code{fitTsfm}.} + +\item{se.type}{one of "Default", "HC" or "HAC"; option for computing +HC/HAC standard errors and t-statistics. Default is "Default".} + +\item{...}{futher arguments passed to or from other methods.} + +\item{x}{an object of class \code{summary.tsfm}.} + +\item{digits}{number of significants digits to use when printing. +Default is 3.} + +\item{trim}{option to supress labels and legend in the summary. When +\code{TRUE}, only the coefficient matrx with standard eroors is printed. +Default is \code{FALSE}.} +} +\value{ +Returns an object of class \code{summary.tsfm}. +The print method for class \code{summary.tsfm} outputs the call, +coefficients (with standard errors and t-statistics), r-squared and +residual volatilty (under the homoskedasticity assumption) for all assets. + +Object of class \code{summary.tsfm} is a list of length N + 2 containing: +\item{call}{the function call to \code{fitTsfm}} +\item{se.type}{standard error type as input} +\item{sum.list}{list of summaries of the N fit objects (of class \code{lm}, +\code{lmRob} or \code{lars}) for each asset in the factor model.} +} +\description{ +\code{summary} method for object of class \code{tsfm}. +Returned object is of class {summary.tsfm}. +} +\details{ +The default \code{summary} method for a fitted \code{lm} object +computes the standard errors and t-statistics under the assumption of +homoskedasticty. Argument \code{se.type} gives the option to compute +heteroskedasticity-consistent (HC) or +heteroskedasticity-autocorrelation-consistent (HAC) standard errors and +t-statistics using \code{\link[lmtest]{coeftest}}. This option is meaningful +only if \code{fit.method = "OLS" or "DLS"}. + +Standard errors are currently not available for +\code{variable.selection="lars"} as there seems to be no consensus on a +statistically valid method of calculating standard errors for the lasso +predictions. +} +\examples{ +data(managers) +fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), + factor.names=colnames(managers[,7:9]), + data=managers) + +# summary of factor model fit for all assets +summary(fit, "HAC") + +# summary of lm fit for a single asset +summary(fit$asset.fit[[1]]) +} +\author{ +Sangeetha Srinivasan & Yi-An Chen. +} +\seealso{ +\code{\link{fitTsfm}}, \code{\link[stats]{summary.lm}} +} + From noreply at r-forge.r-project.org Fri Mar 20 00:01:59 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 20 Mar 2015 00:01:59 +0100 (CET) Subject: [Returnanalytics-commits] r3618 - in pkg/FactorAnalytics: . R man Message-ID: <20150319230200.010B2183BFE@r-forge.r-project.org> Author: chenyian Date: 2015-03-20 00:01:59 +0100 (Fri, 20 Mar 2015) New Revision: 3618 Modified: pkg/FactorAnalytics/DESCRIPTION pkg/FactorAnalytics/R/fitTsfmUpDn.r pkg/FactorAnalytics/R/plot.tsfm.r pkg/FactorAnalytics/R/plot.tsfmUpDn.r pkg/FactorAnalytics/R/predict.tsfmUpDn.r pkg/FactorAnalytics/man/fitTsfmUpDn.Rd pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd Log: version 2.0.14 1. Add single market factor line and Robust up/dn fitted line for plot.tsfmUpDn.r. 2. Change the corresponding plot.tsfmUpDn.Rd file. 3. Add a new legend. Modified: pkg/FactorAnalytics/DESCRIPTION =================================================================== --- pkg/FactorAnalytics/DESCRIPTION 2015-03-16 20:41:50 UTC (rev 3617) +++ pkg/FactorAnalytics/DESCRIPTION 2015-03-19 23:01:59 UTC (rev 3618) @@ -1,36 +1,36 @@ -Package: factorAnalytics -Type: Package -Title: Factor Analytics -Version: 2.0.14 -Date: 2015-03-15 -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.14 +Date:2015-03-19 +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/fitTsfmUpDn.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmUpDn.r 2015-03-16 20:41:50 UTC (rev 3617) +++ pkg/FactorAnalytics/R/fitTsfmUpDn.r 2015-03-19 23:01:59 UTC (rev 3618) @@ -39,9 +39,13 @@ #' \code{fitted}, \code{residuals} and \code{fmCov} can be applied as well. #' #' An object of class \code{"tsfmUpDn"} is a list containing \code{Up} and \code{Dn}: -#' \item{Up}{An object of \code{tsfm} fitted by \code{fitTsfm} for the up market.} -#' \item{Dn}{An object of \code{tsfm} fitted by \code{fitTsfm} for the down market.} +#' \item{Up}{An object of \code{tsfm} fitted by \code{fitTsfm} for the up market;} +#' \item{Dn}{An object of \code{tsfm} fitted by \code{fitTsfm} for the down market;} #' +#' and others useful items: +#' \item{call}{Function call.} +#' \item{data}{Original data used but converted to \code{xts} class.} +#' #' Each object of \code{tsfm} contains : #' \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 @@ -100,10 +104,11 @@ data=data, fit.method=c("OLS","DLS","Robust"), control=fitTsfm.control(...),...) { + call <- match.call() + if (is.null(mkt.name)){ stop("Missing argument: mkt.name has to be specified for up and down market model.") } - # convert data into an xts object and hereafter work with xts objects data.xts <- checkData(data) @@ -114,7 +119,7 @@ dat.xts <- merge(data.xts[,asset.names], data.xts[,mkt.name]) ### After merging xts objects, the spaces in names get converted to periods - # convert all asset and factor returns to excess return form if specified + # convert all asset and factor returns to excess returns 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)))) @@ -124,18 +129,16 @@ # up market dataUp.xts <- dat.xts[mkt >= 0] - fitUp <- fitTsfm(asset.names=asset.names,factor.names=mkt.name,mkt.name=mkt.name,rf.name=rf.name, - data=dataUp.xts,fit.method=fit.method,variable.selection="none", - control=control) + fitUp <- fitTsfm(asset.names=asset.names,factor.names=mkt.name,mkt.name=mkt.name,rf.name=NULL, + data=dataUp.xts,fit.method=fit.method,control=control) # down market dataDn.xts <- dat.xts[mkt < 0] - fitDn <- fitTsfm(asset.names=asset.names,factor.names=mkt.name,mkt.name=mkt.name,rf.name=rf.name, - data=dataDn.xts,fit.method=fit.method,variable.selection="none", - control=control) + fitDn <- fitTsfm(asset.names=asset.names,factor.names=mkt.name,mkt.name=mkt.name,rf.name=NULL, + data=dataDn.xts,fit.method=fit.method,control=control) - result <- list(Up = fitUp, Dn = fitDn) + result <- list(Up = fitUp, Dn = fitDn, call= call, data=dat.xts) class(result) <- "tsfmUpDn" return(result) } Modified: pkg/FactorAnalytics/R/plot.tsfm.r =================================================================== --- pkg/FactorAnalytics/R/plot.tsfm.r 2015-03-16 20:41:50 UTC (rev 3617) +++ pkg/FactorAnalytics/R/plot.tsfm.r 2015-03-19 23:01:59 UTC (rev 3618) @@ -1,462 +1,464 @@ -#' @title Plots from a fitted time series factor model -#' -#' @description Generic \code{plot} method for object of class \code{tsfm}. -#' Plots chosen characteristic(s) for one or more assets. -#' -#' @details -#' -#' The function can be used for group plots and individual plots. User can -#' select the type of plot either from the menu prompt (default) or directly -#' via argument \code{which}. -#' -#' In case multiple plots are needed, the menu is repeated after each plot -#' (enter 0 to exit). User can also input a numeric vector of plot options via -#' \code{which}. -#' -#' For group plots (the default), the first \code{max.show} assets are plotted. -#' -#' Setting \code{plot.single=TRUE} enables individual plots. If there is more -#' than one asset fit by \code{x}, \code{asset.name} should be specified. -#' However, if the \code{tsfm} object \code{x} only contains one asset?s factor -#' model fit, plot.tsfm can infer \code{asset.name} without user input. -#' -#' CUSUM plots (individual asset plot options 10, 11 and 12) are applicable -#' only for \code{fit.method="OLS"}. -#' -#' Rolling estimates (individual asset plot option 13) is not applicable for -#' \code{variable.slection="lars"}. -#' -#' @param x an object of class \code{tsfm} produced by \code{fitTsfm}. -#' @param which a number to indicate the type of plot. If a subset of the plots -#' is required, specify a subset of the numbers 1:10 for group plots and 1:16 -#' for individual plots. If \code{which=NULL} (default), the following menu -#' appears: \cr \cr -#' For plots of a group of assets: \cr -#' 1 = Factor model coefficients: Alpha, \cr -#' 2 = Factor model coefficients: Betas, \cr -#' 3 = Actual and Fitted asset returns, \cr -#' 4 = R-squared, \cr -#' 5 = Residual Volatility,\cr -#' 6 = Factor Model Residual Correlation \cr -#' 7 = Factor Model Correlation,\cr -#' 8 = Factor Contribution to SD,\cr -#' 9 = Factor Contribution to ES,\cr -#' 10 = Factor Contribution to VaR \cr \cr -#' For individual asset plots:\cr -#' 1 = Actual and fitted returns,\cr -#' 2 = Residuals and fitted returns, \cr -#' 3 = Scale-Location plot, \cr -#' 4 = Residuals with standard error bands, \cr -#' 5 = Time series of squared residuals, \cr -#' 6 = Time series of absolute residuals,\cr -#' 7 = SACF and PACF of residuals,\cr -#' 8 = SACF and PACF of squared residuals,\cr -#' 9 = SACF and PACF of absolute residuals,\cr -#' 10 = Density estimate of residuals, \cr -#' 11 = Histogram of residuals with normal curve overlayed,\cr -#' 12 = Normal QQ-plot of residuals,\cr -#' 13 = CUSUM test-Recursive residuals,\cr -#' 14 = CUSUM test-OLS residuals,\cr -#' 15 = Recursive estimates (RE) test of OLS regression coefficients,\cr -#' 16 = Rolling estimates over a 24-period observation window -#' @param max.show maximum number of assets in a given plot. Default is 6. -#' @param plot.single logical; If \code{TRUE} plots the characteristics of an -#' individual asset's factor model. The type of plot is given by -#' \code{which}. Default is \code{FALSE}. -#' @param asset.name name of the individual asset to be plotted. Is necessary -#' if \code{x} contains multiple asset fits and \code{plot.single=TRUE}. -#' @param colorset color palette to use for all the plots. Default is -#' \code{c(1:12)}. The 1st element will be used for individual time series -#' plots or the 1st series plotted, the 2nd element for the 2nd object in the -#' plot and so on. -#' @param legend.loc places a legend into one of nine locations on the chart: -#' "bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", -#' "right", or "center". Default is "bottomright". Use \code{legend.loc=NULL} -#' to suppress the legend. -#' @param las one of {0, 1, 2, 3} to set the direction of axis labels, same as -#' in \code{plot}. Default here is 1. -#' @param VaR.method a method for computing VaR; one of "modified", "gaussian", -#' "historical" or "kernel". VaR is computed using -#' \code{\link[PerformanceAnalytics]{VaR}}. Default is "historical". -#' @param ... further arguments to be passed to other plotting functions. -#' -#' @author Eric Zivot, Sangeetha Srinivasan and Yi-An Chen -#' -#' @seealso \code{\link{fitTsfm}} and \code{\link{summary.tsfm}} for details -#' about the time series factor model fit, extractor functions and summary -#' statistics. -#' -#' \code{\link[strucchange]{efp}} for CUSUM tests. -#' -#' \code{\link[xts]{plot.xts}}, -#' \code{\link[PerformanceAnalytics]{chart.TimeSeries}}, -#' \code{\link[PerformanceAnalytics]{chart.ACFplus}}, -#' \code{\link[PerformanceAnalytics]{chart.Histogram}}, -#' \code{\link[PerformanceAnalytics]{chart.QQPlot}}, -#' \code{\link[graphics]{barplot}}, \code{\link[lattice]{barchart}} and -#' \code{\link[corrplot]{corrplot}} for plotting methods used. -#' -#' \code{\link{fmSdDecomp}}, \code{\link{fmEsDecomp}}, -#' \code{\link{fmVaRDecomp}} for factor model risk measures. -#' -#' @examples -#' -#' # load data from the database -#' data(managers) -#' fit.macro <- fitTsfm(asset.names=colnames(managers[,(1:6)]), -#' factor.names=colnames(managers[,(7:8)]), -#' rf.name="US.3m.TR", data=managers) -#' -#' # for group plots (default), user can select type from menu prompt -#' # menu is repeated to get multiple types of plots based on the same fit -#' # plot(fit.macro) -#' -#' # plot specific option(s) though which -#' # plot the factor betas of 1st 4 assets fitted above -#' plot(fit.macro, max.show=4, which=2) -#' -#' # plot factor model return correlation; angular order of the eigenvectors -#' plot(fit.macro, which=7, order="AOE", method="ellipse", tl.pos = "d") -#' -#' # for individual plots: set plot.single=TRUE; specify asset.name -#' # histogram of residuals from an individual asset's factor model fit -#' plot(fit.macro, plot.single=TRUE, asset.name="HAM1", which=8) -#' -#' @importFrom PerformanceAnalytics chart.TimeSeries chart.ACFplus -#' chart.Histogram chart.QQPlot -#' @importFrom lattice barchart panel.barchart panel.grid -#' @importFrom corrplot corrplot -#' @importFrom strucchange efp -#' @importFrom robust lmRob -#' -#' @method plot tsfm -#' @export - -plot.tsfm <- function(x, which=NULL, max.show=6, plot.single=FALSE, - asset.name, colorset=(1:12), legend.loc="topleft", las=1, - VaR.method="historical", ...) { - - which.vec <- which - which <- which[1] - - if (plot.single==TRUE) { - - if (missing(asset.name) && length(x$asset.names)>1) { - stop("Missing input: 'asset.name' is required if plot.single is TRUE and - the factor model fits multiple assets.") - } else if (length(x$asset.names)==1) { - i <- x$asset.names[1] - } else { - i <- asset.name - } - # extract info from the fitTsfm object - plotData <- merge.xts(x$data[,i], fitted(x)[,i]) - colnames(plotData) <- c("Actual","Fitted") - Residuals <- residuals(x)[,i] - plotData2 <- merge.xts(Residuals, fitted(x)[,i]) - colnames(plotData2) <- c("Residuals","Fitted") - fit <- x$asset.fit[[i]] - - # plot selection - repeat { - if (is.null(which)) { - which <- - menu(c("Actual vs fitted asset returns", - "Residuals vs fitted asset returns", - "Scale-Location plot", - "Residuals with standard error bands", - "Time series of squared residuals", - "Time series of absolute residuals", - "SACF and PACF of residuals", - "SACF and PACF of squared residuals", - "SACF and PACF of absolute residuals", - "Density Estimate of Residuals", - "Histogram of residuals with normal curve overlayed", - "Normal qq-plot of residuals", - "CUSUM test-Recursive residuals", - "CUSUM test-OLS residuals", - "Recursive estimates (RE) test of OLS regression coefficients", - "Rolling estimates over a 24-period observation window"), - title="\nMake a plot selection (or 0 to exit):") - } - - par(las=las) # default horizontal axis labels - - switch(which, - "1L" = { - ## time series plot of actual and fitted asset returns - chart.TimeSeries(plotData, main=paste("Actual and Fitted:",i), - colorset=colorset, xlab="", ylab="Asset returns", - legend.loc=legend.loc, pch=NULL, las=las, ...) - }, "2L" = { - ## residuals vs fitted asset returns - plot(fit, which=1, main=paste("Residuals vs Fitted Returns:",i), - caption=NA, sub.caption="", las=las, ...) - }, "3L" = { - ## square root of absolute residuals vs fitted asset returns - plot(fit, which=3, main=paste("Scale-Location plot:",i), - caption=NA, sub.caption="", las=las, ...) - }, "4L" = { - ## time series plot of residuals with standard error bands - chart.TimeSeries(Residuals, main=paste("Residuals:",i), - colorset=colorset, xlab="", ylab="Residuals", - lwd=2, lty="solid", las=las, ...) - abline(h=1.96*x$resid.sd[i], lwd=2, lty="dotted", col="red") - abline(h=-1.96*x$resid.sd[i], lwd=2, lty="dotted", col="red") - legend(x=legend.loc, lty=c("solid","dotted"), - col=c(colorset[1],"red"), lwd=2, - legend=c("Residuals",expression("\u00b1 1.96"*sigma))) - }, "5L" = { - ## time series plot of squared residuals - chart.TimeSeries(Residuals^2, colorset=colorset, xlab="", - ylab=" Squared Residuals", - main=paste("Squared Residuals:",i), - legend.loc=legend.loc, pch=NULL, las=las, ...) - }, "6L" = { - ## time series plot of absolute residuals - chart.TimeSeries(abs(Residuals), colorset=colorset, xlab="", - ylab="Absolute Residuals", - main=paste("Absolute Residuals:",i), - legend.loc=legend.loc, pch=NULL, las=las, ...) - }, "7L" = { - ## SACF and PACF of residuals - chart.ACFplus(Residuals, col=colorset[1], - main=paste("SACF & PACF - Residuals:",i), ...) - }, "8L" = { - ## SACF and PACF of squared residuals - chart.ACFplus(Residuals^2, col=colorset[1], ..., - main=paste("SACF & PACF - Squared residuals:",i)) - }, "9L" = { - ## SACF and PACF of absolute residuals - chart.ACFplus(abs(Residuals), col=colorset[1], ..., - main=paste("SACF & PACF - Absolute Residuals:",i)) - }, "10L" = { - ## density estimate of residuals - plot(density(Residuals), xlab="Return residuals", - colorset=colorset, main=paste("Density estimate of Residuals:",i), ...) - rug(Residuals) - }, "11L" = { - ## histogram of residuals with normal curve overlayed - methods <- c("add.density","add.normal","add.rug") - chart.Histogram(Residuals, xlab="Return residuals", - methods=methods, colorset=colorset, - main=paste("Histogram of Residuals:",i), ...) - }, "12L" = { - ## normal qq-plot of residuals - chart.QQPlot(Residuals, envelope=0.95, col=colorset, - main=paste("QQ-plot of Residuals:",i), ...) - legend(x=legend.loc, col="red", lty="dotted", lwd=1, - legend=c("0.95 confidence envelope")) - }, "13L" = { - ## Recursive CUSUM test - if (!x$fit.method=="OLS") { - stop("CUSUM analysis applicable only for 'OLS' fit.method.") - } - cusum.rec <- efp(formula(fit), type="Rec-CUSUM", data=fit$model) - plot(cusum.rec, main=paste("Recursive CUSUM test:",i), las=las, - col=colorset, ...) - }, "14L" = { - ## OLS-based CUSUM test - if (!x$fit.method=="OLS") { - stop("CUSUM analysis applicable only for 'OLS' fit.method.") - } - cusum.ols <- efp(formula(fit), type="OLS-CUSUM", data=fit$model) - plot(cusum.ols, main=paste("OLS-based CUSUM test:",i), las=las, - col=colorset, ...) - }, "15L" = { - ## Recursive estimates (RE) test of OLS regression coefficients - if (!x$fit.method=="OLS") { - stop("CUSUM analysis applicable only for 'OLS' fit.method.") - } - cusum.est <- efp(formula(fit), type="RE", data=fit$model) - plot(cusum.est, functional=NULL, col=colorset, las=0, - main=paste("RE test (Recursive estimates test):",i), ...) - }, "16L" = { - ## Rolling estimates over 24-period observation window - if (x$fit.method=="OLS") { - rollReg <- function(data.z, formula) { - coef(lm(formula, data=as.data.frame(data.z))) - } - reg.z <- zoo(fit$model, as.Date(rownames(fit$model))) - rollReg.z <- rollapply(reg.z, FUN=rollReg, formula(fit), - width=24, by.column=FALSE, align="right") - } else if (x$fit.method=="DLS") { - # get decay factor - if (as.character(x$call["decay"])=="NULL") { - decay <- 0.95 # default value for the decay factor - } else { - decay <- as.numeric(as.character(x$call["decay"])) - } - # calculate exp. decaying weights for 24-period window - w <- decay^seq(23,0,-1) - w <- w/sum(w) # weights sum to unity - rollReg.w <- function(data.z, formula, w) { - coef(lm(formula, weights=w, data=as.data.frame(data.z))) - } - reg.z <- zoo(fit$model[-length(fit$model)], - as.Date(rownames(fit$model))) - rollReg.z <- rollapply(reg.z, FUN=rollReg.w, formula(fit), w, - width=24, by.column=FALSE, align="right") - } else if (x$fit.method=="Robust") { - rollReg.Rob <- function(data.z, formula) { - coef(lmRob(formula=formula, data=as.data.frame(data.z))) - } - reg.z <- zoo(fit$model, as.Date(rownames(fit$model))) - rollReg.z <- rollapply(reg.z, width=24, FUN=rollReg.Rob, - formula(fit), by.column=FALSE, - align="right") - } else if (is.null(x$fit.method)) { - stop("Rolling estimates is not available for 'lars' fits.") - } - par(las=0) - plot(rollReg.z, ..., las=las, - main=paste("Rolling estimates (24-period obs window):",i)) - par(las=las) - }, - invisible() - ) - # repeat menu if user didn't choose to exit from the plot options - if (which==0 || length(which.vec)==1) {break} - if (length(which.vec)>1) { - which.vec <- which.vec[-1] - which <- which.vec[1] - par(ask=TRUE) - } else {which=NULL} - } - } else { # start of group asset plots - - # plot selection - repeat { - if (is.null(which)) { - which <- - menu(c("Factor model coefficients: Alpha", - "Factor model coefficients: Betas", - "Actual and Fitted asset returns", - "R-squared", - "Residual Volatility", - "Factor Model Residual Correlation", - "Factor Model Return Correlation", - "Factor Contribution to SD", - "Factor Contribution to ES", - "Factor Contribution to VaR"), - title="\nMake a plot selection (or 0 to exit):") - } - - par(las=las) # default horizontal axis labels - - switch(which, - "1L" = { - ## Factor model coefficients: Alpha - barplot(coef(x)[,1], main="Factor model Alpha (Intercept)", - names.arg=rownames(coef(x)), col="darkblue", las=las, - horiz=TRUE, ...) - abline(v=0, lwd=1, lty=1, col=1) - }, - "2L" = { - ## Factor model coefficients: Betas - k <- ncol(coef(x))-1 - if (k > max.show) { - cat(paste("Displaying only the first", max.show,"factor betas, as the number of factors > 'max.show' =", max.show)) - k <- max.show - } - par(mfrow=c(ceiling(k/2),2)) - for (i in 2:(k+1)) { - main=paste(colnames(coef(x))[i], "factor Betas") - barplot(coef(x)[,i], main=main, names.arg=rownames(coef(x)), - col="darkblue", las=las, horiz=TRUE, ...) - abline(v=0, lwd=1, lty=1, col=1) - } - par(mfrow=c(1,1)) - }, - "3L" = { - ## Actual and Fitted asset returns - n <- length(x$asset.names) - if (n > max.show) { - cat(paste("Displaying only the first", max.show, "assets, since the number of assets > 'max.show'")) - n <- max.show - } - par(mfrow=c(ceiling(n/2),2)) - for (i in 1:n) { - plotData <- merge.xts(x$data[,i], fitted(x)[,i]) - colnames(plotData) <- c("Actual","Fitted") - main <- paste("Actual vs Fitted:", x$asset.names[i]) - chart.TimeSeries(plotData, colorset=colorset, main=main, - xlab="", ylab="Asset returns", - legend.loc=legend.loc, pch=NULL, las=las,...) - } - par(mfrow=c(1,1)) - }, - "4L" ={ - ## R-squared - plot( - barchart(x$r2, main="R-squared values", xlab="", - col="darkblue", ...) - ) - }, - "5L" = { - ## Residual Volatility - plot( - barchart(x$resid.sd, main="Residual volatility", xlab="", - col="darkblue", ...) - ) - }, - "6L" = { - ## Factor Model Residual Correlation - cor.resid <- cor(residuals(x), use="pairwise.complete.obs") - corrplot(cor.resid, ...) - # mtext("pairwise complete obs", line=0.5) - }, - "7L" = { - ## Factor Model Return Correlation - cor.fm <- cov2cor(fmCov(x)) - corrplot(cor.fm, ...) - # mtext("pairwise complete obs", line=0.5) - }, - "8L" = { - ## Factor Percentage Contribution to SD - pcSd.fm <- fmSdDecomp(x)$pcSd - plot( - barchart(pcSd.fm, main="Factor % Contribution to SD", xlab="", - auto.key=list(space="bottom",columns=3, - points=FALSE,rectangles=TRUE), - par.settings=list(superpose.polygon=list(col=colorset)), - panel=function(...){panel.grid(h=0, v=-1); - panel.barchart(...)}, ...) - ) - }, - "9L"={ - ## Factor Percentage Contribution to ES - pcES.fm <- fmEsDecomp(x, method=VaR.method)$pcES - plot( - barchart(pcES.fm, main="Factor % Contribution to ES", xlab="", - auto.key=list(space="bottom",columns=3, - points=FALSE,rectangles=TRUE), - par.settings=list(superpose.polygon=list(col=colorset)), - panel=function(...){panel.grid(h=0, v=-1); - panel.barchart(...)}, ...) - ) - }, - "10L" ={ - ## Factor Percentage Contribution to VaR - pcVaR.fm <- fmVaRDecomp(x, method=VaR.method)$pcVaR - plot( - barchart(pcVaR.fm, main="Factor % Contribution to VaR", - xlab="", auto.key=list(space="bottom",columns=3, - points=FALSE,rectangles=TRUE), - par.settings=list(superpose.polygon=list(col=colorset)), - panel=function(...){panel.grid(h=0, v=-1); - panel.barchart(...)}, ...) - ) - }, - invisible() - ) - # repeat menu if user didn't choose to exit from the plot options - if (which==0 || length(which.vec)==1) {break} - if (length(which.vec)>1) { - which.vec <- which.vec[-1] - which <- which.vec[1] - par(ask=TRUE) - } else {which=NULL} - } - } # end of group plots -} +#' @title Plots from a fitted time series factor model +#' +#' @description Generic \code{plot} method for object of class \code{tsfm}. +#' Plots chosen characteristic(s) for one or more assets. +#' +#' @details +#' +#' The function can be used for group plots and individual plots. User can +#' select the type of plot either from the menu prompt (default) or directly +#' via argument \code{which}. +#' +#' In case multiple plots are needed, the menu is repeated after each plot +#' (enter 0 to exit). User can also input a numeric vector of plot options via +#' \code{which}. +#' +#' For group plots (the default), the first \code{max.show} assets are plotted. +#' +#' Setting \code{plot.single=TRUE} enables individual plots. If there is more +#' than one asset fit by \code{x}, \code{asset.name} should be specified. +#' However, if the \code{tsfm} object \code{x} only contains one asset?s factor +#' model fit, plot.tsfm can infer \code{asset.name} without user input. +#' +#' CUSUM plots (individual asset plot options 10, 11 and 12) are applicable +#' only for \code{fit.method="OLS"}. +#' +#' Rolling estimates (individual asset plot option 13) is not applicable for +#' \code{variable.slection="lars"}. +#' +#' @param x an object of class \code{tsfm} produced by \code{fitTsfm}. +#' @param which a number to indicate the type of plot. If a subset of the plots +#' is required, specify a subset of the numbers 1:10 for group plots and 1:16 +#' for individual plots. If \code{which=NULL} (default), the following menu +#' appears: \cr \cr +#' For plots of a group of assets: \cr +#' 1 = Factor model coefficients: Alpha, \cr +#' 2 = Factor model coefficients: Betas, \cr +#' 3 = Actual and Fitted asset returns, \cr +#' 4 = R-squared, \cr +#' 5 = Residual Volatility,\cr +#' 6 = Factor Model Residual Correlation \cr +#' 7 = Factor Model Correlation,\cr +#' 8 = Factor Contribution to SD,\cr +#' 9 = Factor Contribution to ES,\cr +#' 10 = Factor Contribution to VaR \cr \cr +#' For individual asset plots:\cr +#' 1 = Actual and fitted returns,\cr +#' 2 = Residuals and fitted returns, \cr +#' 3 = Scale-Location plot, \cr +#' 4 = Residuals with standard error bands, \cr +#' 5 = Time series of squared residuals, \cr +#' 6 = Time series of absolute residuals,\cr +#' 7 = SACF and PACF of residuals,\cr +#' 8 = SACF and PACF of squared residuals,\cr +#' 9 = SACF and PACF of absolute residuals,\cr +#' 10 = Density estimate of residuals, \cr +#' 11 = Histogram of residuals with normal curve overlayed,\cr +#' 12 = Normal QQ-plot of residuals,\cr +#' 13 = CUSUM test-Recursive residuals,\cr +#' 14 = CUSUM test-OLS residuals,\cr +#' 15 = Recursive estimates (RE) test of OLS regression coefficients,\cr +#' 16 = Rolling estimates over a 24-period observation window +#' @param max.show maximum number of assets in a given plot. Default is 6. +#' @param plot.single logical; If \code{TRUE} plots the characteristics of an +#' individual asset's factor model. The type of plot is given by +#' \code{which}. Default is \code{FALSE}. +#' @param asset.name name of the individual asset to be plotted. Is necessary +#' if \code{x} contains multiple asset fits and \code{plot.single=TRUE}. +#' @param colorset color palette to use for all the plots. Default is +#' \code{c(1:12)}. The 1st element will be used for individual time series +#' plots or the 1st series plotted, the 2nd element for the 2nd object in the +#' plot and so on. +#' @param legend.loc places a legend into one of nine locations on the chart: +#' "bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", +#' "right", or "center". Default is "bottomright". Use \code{legend.loc=NULL} +#' to suppress the legend. +#' @param las one of {0, 1, 2, 3} to set the direction of axis labels, same as +#' in \code{plot}. Default here is 1. +#' @param VaR.method a method for computing VaR; one of "modified", "gaussian", +#' "historical" or "kernel". VaR is computed using +#' \code{\link[PerformanceAnalytics]{VaR}}. Default is "historical". +#' @param ... further arguments to be passed to other plotting functions. +#' +#' @author Eric Zivot, Sangeetha Srinivasan and Yi-An Chen +#' +#' @seealso \code{\link{fitTsfm}} and \code{\link{summary.tsfm}} for details +#' about the time series factor model fit, extractor functions and summary +#' statistics. +#' +#' \code{\link[strucchange]{efp}} for CUSUM tests. +#' +#' \code{\link[xts]{plot.xts}}, +#' \code{\link[PerformanceAnalytics]{chart.TimeSeries}}, +#' \code{\link[PerformanceAnalytics]{chart.ACFplus}}, +#' \code{\link[PerformanceAnalytics]{chart.Histogram}}, +#' \code{\link[PerformanceAnalytics]{chart.QQPlot}}, +#' \code{\link[graphics]{barplot}}, \code{\link[lattice]{barchart}} and +#' \code{\link[corrplot]{corrplot}} for plotting methods used. +#' +#' \code{\link{fmSdDecomp}}, \code{\link{fmEsDecomp}}, +#' \code{\link{fmVaRDecomp}} for factor model risk measures. +#' +#' @examples +#' +#' # load data from the database +#' data(managers) [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3618 From noreply at r-forge.r-project.org Fri Mar 20 00:17:52 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 20 Mar 2015 00:17:52 +0100 (CET) Subject: [Returnanalytics-commits] r3619 - in pkg/FactorAnalytics: R man Message-ID: <20150319231753.0C433183BFE@r-forge.r-project.org> Author: chenyian Date: 2015-03-20 00:17:52 +0100 (Fri, 20 Mar 2015) New Revision: 3619 Modified: pkg/FactorAnalytics/R/plot.tsfm.r pkg/FactorAnalytics/man/fitTsfm.Rd pkg/FactorAnalytics/man/fitTsfm.control.Rd pkg/FactorAnalytics/man/plot.tsfm.Rd pkg/FactorAnalytics/man/predict.tsfmUpDn.Rd pkg/FactorAnalytics/man/summary.tsfm.Rd Log: debug so Rd2pdf can work. Modified: pkg/FactorAnalytics/R/plot.tsfm.r =================================================================== --- pkg/FactorAnalytics/R/plot.tsfm.r 2015-03-19 23:01:59 UTC (rev 3618) +++ pkg/FactorAnalytics/R/plot.tsfm.r 2015-03-19 23:17:52 UTC (rev 3619) @@ -17,7 +17,7 @@ #' #' Setting \code{plot.single=TRUE} enables individual plots. If there is more #' than one asset fit by \code{x}, \code{asset.name} should be specified. -#' However, if the \code{tsfm} object \code{x} only contains one asset?s factor +#' However, if the \code{tsfm} object \code{x} only contains a single asset factor #' model fit, plot.tsfm can infer \code{asset.name} without user input. #' #' CUSUM plots (individual asset plot options 10, 11 and 12) are applicable Modified: pkg/FactorAnalytics/man/fitTsfm.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfm.Rd 2015-03-19 23:01:59 UTC (rev 3618) +++ pkg/FactorAnalytics/man/fitTsfm.Rd 2015-03-19 23:17:52 UTC (rev 3619) @@ -1,193 +1,194 @@ -% Generated by roxygen2 (4.0.2): do not edit by hand -\name{fitTsfm} -\alias{coef.tsfm} -\alias{fitTsfm} -\alias{fitted.tsfm} -\alias{residuals.tsfm} -\title{Fit a time series factor model using time series regression} -\usage{ -fitTsfm(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"), - control = fitTsfm.control(...), ...) - -\method{coef}{tsfm}(object, ...) - -\method{fitted}{tsfm}(object, ...) - -\method{residuals}{tsfm}(object, ...) -} -\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 returns. 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}}} - -\item{object}{a fit object of class \code{tsfm} which is returned by -\code{fitTsfm}} -} -\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{mkt.name}{mkt.name 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{ -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. - -Argument \code{mkt.name} can be used to add market-timing factors to any of -the above methods. Please refer to \code{\link{fitTsfmMT}}, a wrapper to -\code{fitTsfm} for details. - -\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) -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=1) -# group plot; type selected from menu prompt; auto-looped for multiple plots -# plot(fit) - - -# example using "subsets" variable selection -fit.sub <- fitTsfm(asset.names=colnames(managers[,(1:6)]), - 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") -} -\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. -} - +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/fitTsfm.R +\name{fitTsfm} +\alias{coef.tsfm} +\alias{fitTsfm} +\alias{fitted.tsfm} +\alias{residuals.tsfm} +\title{Fit a time series factor model using time series regression} +\usage{ +fitTsfm(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"), + control = fitTsfm.control(...), ...) + +\method{coef}{tsfm}(object, ...) + +\method{fitted}{tsfm}(object, ...) + +\method{residuals}{tsfm}(object, ...) +} +\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 returns. 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}}} + +\item{object}{a fit object of class \code{tsfm} which is returned by +\code{fitTsfm}} +} +\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{mkt.name}{mkt.name 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{ +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. + +Argument \code{mkt.name} can be used to add market-timing factors to any of +the above methods. Please refer to \code{\link{fitTsfmMT}}, a wrapper to +\code{fitTsfm} for details. + +\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) +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=1) +# group plot; type selected from menu prompt; auto-looped for multiple plots +# plot(fit) + + +# example using "subsets" variable selection +fit.sub <- fitTsfm(asset.names=colnames(managers[,(1:6)]), + 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") +} +\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. +} + Modified: pkg/FactorAnalytics/man/fitTsfm.control.Rd =================================================================== --- pkg/FactorAnalytics/man/fitTsfm.control.Rd 2015-03-19 23:01:59 UTC (rev 3618) +++ pkg/FactorAnalytics/man/fitTsfm.control.Rd 2015-03-19 23:17:52 UTC (rev 3619) @@ -1,170 +1,171 @@ -% Generated by roxygen2 (4.0.2): do not edit by hand -\name{fitTsfm.control} -\alias{fitTsfm.control} -\title{List of control parameters for \code{fitTsfm}} -\usage{ -fitTsfm.control(decay = 0.95, weights, model = TRUE, x = FALSE, - y = FALSE, qr = TRUE, nrep = NULL, efficiency = 0.9, scope, scale, - direction, trace = FALSE, steps = 1000, k = 2, nvmin = 1, nvmax = 8, - force.in = NULL, force.out = NULL, method, really.big = FALSE, type, - normalize = TRUE, eps = .Machine$double.eps, max.steps, - lars.criterion = "Cp", K = 10) -} -\arguments{ -\item{decay}{a scalar in (0, 1] to specify the decay factor for "DLS". -Default is 0.95.} - -\item{weights}{an optional vector of weights to be used in the fitting -process for \code{fit.method="OLS","Robust"}, or -\code{variable.selection="subsets"}. Should be \code{NULL} or a numeric -vector. The length of \code{weights} must be the same as the number of -observations. The weights must be nonnegative and it is strongly -recommended that they be strictly positive.} - -\item{model,x,y,qr}{logicals passed to \code{lm} for -\code{fit.method="OLS"}. If \code{TRUE} the corresponding components of the -fit (the model frame, the model matrix, the response, the QR decomposition) -are returned.} - -\item{nrep}{the number of random subsamples to be drawn for -\code{fit.method="Robust"}. If the data set is small and "Exhaustive" -resampling is being used, the value of \code{nrep} is ignored.} - -\item{efficiency}{the asymptotic efficiency of the final estimate for -\code{fit.method="Robust"}. Default is 0.9.} - -\item{scope}{defines the range of models examined in the \code{"stepwise"} -search. This should be either a single formula, or a list containing -components \code{upper} and \code{lower}, both formulae. See -\code{\link[stats]{step}} for how to specify the formulae and usage.} - -\item{scale}{optional parameter for \code{variable.selection="stepwise"}. -The argument is passed to \code{\link[stats]{step}} or -\code{\link[robust]{step.lmRob}} as appropriate.} - -\item{direction}{the mode of \code{"stepwise"} search, can be one of "both", -"backward", or "forward", with a default of "both". If the \code{scope} -argument is missing the default for \code{direction} is "backward".} - -\item{trace}{If positive (or, not \code{FALSE}), info is printed during the -running of \code{\link[stats]{step}}, \code{\link[robust]{step.lmRob}}, -\code{\link[lars]{lars}} or \code{\link[lars]{cv.lars}} as relevant. Larger -values may give more detailed information. Default is \code{FALSE}.} - -\item{steps}{the maximum number of steps to be considered for -\code{"stepwise"}. Default is 1000 (essentially as many as required). It is -typically used to stop the process early.} - -\item{k}{the multiple of the number of degrees of freedom used for the -penalty in \code{"stepwise"}. Only \code{k = 2} gives the genuine AIC. -\code{k = log(n)} is sometimes referred to as BIC or SBC. Default is 2.} - -\item{nvmin}{minimum size of subsets to examine for \code{"subsets"}. -Default is 1.} - -\item{nvmax}{maximum size of subsets to examine for \code{"subsets"}. -Default is 8.} - -\item{force.in}{index to columns of design matrix that should be in all -models for \code{"subsets"}. Default is \code{NULL}.} - -\item{force.out}{index to columns of design matrix that should be in no -models for \code{"subsets"}. Default is \code{NULL}.} - -\item{method}{one of "exhaustive", "forward", "backward" or "seqrep" -(sequential replacement) to specify the type of subset search/selection. -Required if \code{variable selection="subsets"} is chosen. Default is -"exhaustive".} - -\item{really.big}{option for \code{"subsets"}; Must be \code{TRUE} to -perform exhaustive search on more than 50 variables.} - -\item{type}{option for \code{"lars"}. One of "lasso", "lar", -"forward.stagewise" or "stepwise". The names can be abbreviated to any -unique substring. Default is "lasso".} - -\item{normalize}{option for \code{"lars"}. If \code{TRUE}, each variable is -standardized to have unit L2 norm, otherwise they are left alone. Default -is \code{TRUE}.} - -\item{eps}{option for \code{"lars"}; An effective zero.} - -\item{max.steps}{Limit the number of steps taken for \code{"lars"}; the -default is \code{8 * min(m, n-intercept)}, with \code{m} the number of -variables, and \code{n} the number of samples. For \code{type="lar"} or -\code{type="stepwise"}, the maximum number of steps is -\code{min(m,n-intercept)}. For \code{type="lasso"} and especially -\code{type="forward.stagewise"}, there can be many more terms, because -although no more than \code{min(m,n-intercept)} variables can be active -during any step, variables are frequently droppped and added as the -algorithm proceeds. Although the default usually guarantees that the -algorithm has proceeded to the saturated fit, users should check.} - -\item{lars.criterion}{an option to assess model selection for the -\code{"lars"} method; one of "Cp" or "cv". See details. Default is "Cp".} - -\item{K}{number of folds for computing the K-fold cross-validated mean -squared prediction error for \code{"lars"}. Default is 10.} -} -\value{ -A list of the above components. This is only meant to be used by -\code{fitTsfm}. -} -\description{ -Creates a list of control parameters for \code{\link{fitTsfm}}. -All control parameters that are not passed to this function are set to -default values. This function is meant for internal use only!! -} -\details{ -This control function is used to process optional arguments passed -via \code{...} to \code{fitTsfm}. These arguments are validated and defaults -are set if necessary before being passed internally to one of the following -functions: \code{\link[stats]{lm}}, \code{\link[robust]{lmRob}}, -\code{\link[stats]{step}}, \code{\link[leaps]{regsubsets}}, -\code{\link[lars]{lars}} and \code{\link[lars]{cv.lars}}. See their -respective help files for more details. The arguments to each of these -functions are listed above in approximately the same order for user -convenience. - -The scalar \code{decay} is used by \code{\link{fitTsfm}} to compute -exponentially decaying weights for \code{fit.method="DLS"}. Alternately, one -can directly specify \code{weights}, a weights vector, to be used with -"OLS" or "Robust". Especially when fitting multiple assets, care should be -taken to ensure that the length of the weights vector matches the number of -observations (excluding cases ignored due to NAs). - -\code{lars.criterion} selects the criterion (one of "Cp" or "cv") to -determine the best fitted model for \code{variable.selection="lars"}. The -"Cp" statistic (defined in page 17 of Efron et al. (2004)) is calculated -using \code{\link[lars]{summary.lars}}. While, "cv" computes the K-fold -cross-validated mean squared prediction error using -\code{\link[lars]{cv.lars}}. -} -\examples{ -\dontrun{ -# check argument list passed by fitTsfm.control -tsfm.ctrl <- fitTsfm.control(method="exhaustive", nvmin=2) -print(tsfm.ctrl) -} - -# used internally by fitTsfm in the example below -data(managers) -fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), - factor.names=colnames(managers[,(7:9)]), - data=managers, variable.selection="subsets", - method="exhaustive", nvmin=2) -} -\author{ -Sangeetha Srinivasan -} -\references{ -Efron, B., Hastie, T., Johnstone, I., & Tibshirani, R. (2004). Least angle -regression. The Annals of statistics, 32(2), 407-499. -} -\seealso{ -\code{\link{fitTsfm}}, \code{\link[stats]{lm}}, -\code{\link[robust]{lmRob}}, \code{\link[stats]{step}}, -\code{\link[leaps]{regsubsets}}, \code{\link[lars]{lars}} and -\code{\link[lars]{cv.lars}} -} - +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/fitTsfm.control.R +\name{fitTsfm.control} +\alias{fitTsfm.control} +\title{List of control parameters for \code{fitTsfm}} +\usage{ +fitTsfm.control(decay = 0.95, weights, model = TRUE, x = FALSE, + y = FALSE, qr = TRUE, nrep = NULL, efficiency = 0.9, scope, scale, + direction, trace = FALSE, steps = 1000, k = 2, nvmin = 1, nvmax = 8, + force.in = NULL, force.out = NULL, method, really.big = FALSE, type, + normalize = TRUE, eps = .Machine$double.eps, max.steps, + lars.criterion = "Cp", K = 10) +} +\arguments{ +\item{decay}{a scalar in (0, 1] to specify the decay factor for "DLS". +Default is 0.95.} + +\item{weights}{an optional vector of weights to be used in the fitting +process for \code{fit.method="OLS","Robust"}, or +\code{variable.selection="subsets"}. Should be \code{NULL} or a numeric +vector. The length of \code{weights} must be the same as the number of +observations. The weights must be nonnegative and it is strongly +recommended that they be strictly positive.} + +\item{model,x,y,qr}{logicals passed to \code{lm} for +\code{fit.method="OLS"}. If \code{TRUE} the corresponding components of the +fit (the model frame, the model matrix, the response, the QR decomposition) +are returned.} + +\item{nrep}{the number of random subsamples to be drawn for +\code{fit.method="Robust"}. If the data set is small and "Exhaustive" +resampling is being used, the value of \code{nrep} is ignored.} + +\item{efficiency}{the asymptotic efficiency of the final estimate for +\code{fit.method="Robust"}. Default is 0.9.} + +\item{scope}{defines the range of models examined in the \code{"stepwise"} +search. This should be either a single formula, or a list containing +components \code{upper} and \code{lower}, both formulae. See +\code{\link[stats]{step}} for how to specify the formulae and usage.} + +\item{scale}{optional parameter for \code{variable.selection="stepwise"}. +The argument is passed to \code{\link[stats]{step}} or +\code{\link[robust]{step.lmRob}} as appropriate.} + +\item{direction}{the mode of \code{"stepwise"} search, can be one of "both", +"backward", or "forward", with a default of "both". If the \code{scope} +argument is missing the default for \code{direction} is "backward".} + +\item{trace}{If positive (or, not \code{FALSE}), info is printed during the +running of \code{\link[stats]{step}}, \code{\link[robust]{step.lmRob}}, +\code{\link[lars]{lars}} or \code{\link[lars]{cv.lars}} as relevant. Larger +values may give more detailed information. Default is \code{FALSE}.} + +\item{steps}{the maximum number of steps to be considered for +\code{"stepwise"}. Default is 1000 (essentially as many as required). It is +typically used to stop the process early.} + +\item{k}{the multiple of the number of degrees of freedom used for the +penalty in \code{"stepwise"}. Only \code{k = 2} gives the genuine AIC. +\code{k = log(n)} is sometimes referred to as BIC or SBC. Default is 2.} + +\item{nvmin}{minimum size of subsets to examine for \code{"subsets"}. +Default is 1.} + +\item{nvmax}{maximum size of subsets to examine for \code{"subsets"}. +Default is 8.} + +\item{force.in}{index to columns of design matrix that should be in all +models for \code{"subsets"}. Default is \code{NULL}.} + +\item{force.out}{index to columns of design matrix that should be in no +models for \code{"subsets"}. Default is \code{NULL}.} + +\item{method}{one of "exhaustive", "forward", "backward" or "seqrep" +(sequential replacement) to specify the type of subset search/selection. +Required if \code{variable selection="subsets"} is chosen. Default is +"exhaustive".} + +\item{really.big}{option for \code{"subsets"}; Must be \code{TRUE} to +perform exhaustive search on more than 50 variables.} + +\item{type}{option for \code{"lars"}. One of "lasso", "lar", +"forward.stagewise" or "stepwise". The names can be abbreviated to any +unique substring. Default is "lasso".} + +\item{normalize}{option for \code{"lars"}. If \code{TRUE}, each variable is +standardized to have unit L2 norm, otherwise they are left alone. Default +is \code{TRUE}.} + +\item{eps}{option for \code{"lars"}; An effective zero.} + +\item{max.steps}{Limit the number of steps taken for \code{"lars"}; the +default is \code{8 * min(m, n-intercept)}, with \code{m} the number of +variables, and \code{n} the number of samples. For \code{type="lar"} or +\code{type="stepwise"}, the maximum number of steps is +\code{min(m,n-intercept)}. For \code{type="lasso"} and especially +\code{type="forward.stagewise"}, there can be many more terms, because +although no more than \code{min(m,n-intercept)} variables can be active +during any step, variables are frequently droppped and added as the +algorithm proceeds. Although the default usually guarantees that the +algorithm has proceeded to the saturated fit, users should check.} + +\item{lars.criterion}{an option to assess model selection for the +\code{"lars"} method; one of "Cp" or "cv". See details. Default is "Cp".} + +\item{K}{number of folds for computing the K-fold cross-validated mean +squared prediction error for \code{"lars"}. Default is 10.} +} +\value{ +A list of the above components. This is only meant to be used by +\code{fitTsfm}. +} +\description{ +Creates a list of control parameters for \code{\link{fitTsfm}}. +All control parameters that are not passed to this function are set to +default values. This function is meant for internal use only!! +} +\details{ +This control function is used to process optional arguments passed +via \code{...} to \code{fitTsfm}. These arguments are validated and defaults +are set if necessary before being passed internally to one of the following +functions: \code{\link[stats]{lm}}, \code{\link[robust]{lmRob}}, +\code{\link[stats]{step}}, \code{\link[leaps]{regsubsets}}, +\code{\link[lars]{lars}} and \code{\link[lars]{cv.lars}}. See their +respective help files for more details. The arguments to each of these +functions are listed above in approximately the same order for user +convenience. + +The scalar \code{decay} is used by \code{\link{fitTsfm}} to compute +exponentially decaying weights for \code{fit.method="DLS"}. Alternately, one +can directly specify \code{weights}, a weights vector, to be used with +"OLS" or "Robust". Especially when fitting multiple assets, care should be +taken to ensure that the length of the weights vector matches the number of +observations (excluding cases ignored due to NAs). + +\code{lars.criterion} selects the criterion (one of "Cp" or "cv") to +determine the best fitted model for \code{variable.selection="lars"}. The +"Cp" statistic (defined in page 17 of Efron et al. (2004)) is calculated +using \code{\link[lars]{summary.lars}}. While, "cv" computes the K-fold +cross-validated mean squared prediction error using +\code{\link[lars]{cv.lars}}. +} +\examples{ +\dontrun{ +# check argument list passed by fitTsfm.control +tsfm.ctrl <- fitTsfm.control(method="exhaustive", nvmin=2) +print(tsfm.ctrl) +} + +# used internally by fitTsfm in the example below +data(managers) +fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), + factor.names=colnames(managers[,(7:9)]), + data=managers, variable.selection="subsets", + method="exhaustive", nvmin=2) +} +\author{ +Sangeetha Srinivasan +} +\references{ +Efron, B., Hastie, T., Johnstone, I., & Tibshirani, R. (2004). Least angle +regression. The Annals of statistics, 32(2), 407-499. +} +\seealso{ +\code{\link{fitTsfm}}, \code{\link[stats]{lm}}, [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3619 From noreply at r-forge.r-project.org Fri Mar 20 00:29:04 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 20 Mar 2015 00:29:04 +0100 (CET) Subject: [Returnanalytics-commits] r3620 - pkg/FactorAnalytics/tests Message-ID: <20150319232904.B469E18636B@r-forge.r-project.org> Author: chenyian Date: 2015-03-20 00:29:04 +0100 (Fri, 20 Mar 2015) New Revision: 3620 Modified: pkg/FactorAnalytics/tests/factorAnalytics.pdf Log: update manual. Modified: pkg/FactorAnalytics/tests/factorAnalytics.pdf =================================================================== --- pkg/FactorAnalytics/tests/factorAnalytics.pdf 2015-03-19 23:17:52 UTC (rev 3619) +++ pkg/FactorAnalytics/tests/factorAnalytics.pdf 2015-03-19 23:29:04 UTC (rev 3620) @@ -202,24 +202,22 @@ << /S /GoTo /D [134 0 R /Fit] >> endobj 146 0 obj << -/Length 1350 +/Length 1349 /Filter /FlateDecode >> stream -x??X?o?6~?_???????/?X??]ZtH???l???m??%??????"%[?#7???<?(?????wGco?a??#|??l???Ey?8???\y$?(?^L'??????7S?',???|??O?Z?LW??d????n???g?{??4????D(?{> -Q;A???6V?3?@1???^?V?6????I??y?$??hn%-?I8?????xo'??<?KgD?1?v?$?i?F???q?%4??^X8`???s5neXpb%? -?? ?JT?~? ?v?aD?(?]???'?O?8O{??|????l?t>J?v?,?P??pRd?????F??)??J?0?b??s?a?U??[~P???????o?(???????r?-?????L?~|??(@$ ???l??{? -?^????cs?x?<?;!?l?5?2W??>OQ?(L8??????t???\o? WZlY?0?] -???????o????????M;? R?j"??1V?m??B??????q??RhQWR??BT -??WnyV?u?[????TkQ???`??gh?%z#?{???g?^????W??z?uB????G???Nz&+6T[??rT?c N??)s???A1???J??????&G?H??x{L3V?97????L????$/?xo?Bc?}???w??<??P??1~?I?/?c?vi?N????W[?1?????ovA????:$??mVIYP?ee}?????V??I5???d????Y??P]fP??m`????^?_]}?k?W?z -??A?????7?????c)??7?????e??Q-??D}{w???H?z`?A??=???4 --W?ZJ?)???>}o6???m?,.?02 -?$????5hxh?0?;??????3?O}?E???ZVx???-?~X??????(IUM=? ?? -???)???j???????_rF???X*? -????#o$??j?? -:?????K?<0????K?~?5??D??XO??????g???h??J?k??7??????+9 +x??Xmo?6??_?o??!?7?X??]ZtH???l???m??%?????~G??-???b??|0D??????w'co?a??#|??????? ?(FqL#o??HJQH??&(No?{o'o?OX?????????b???y??[-2?????? )?AiQ#)?P2?|?4v?^3?m?????b???R?F)????8A?(IE??JZN?pr[?????I?y?JgD?1?N?$?i?F???q?%4??^X8`???s5neXpb%? +?? ?JT?~? ?v?aD?Q,?`?OL?2q??&??8 ?l2?6?O??Fo??1?"&=?????w1???zJ???.??X??\o?{???v?+?<+s;?mE?????^??euX???R???Z???????U?tO?{??(): ?9?f????N'?S?25.????&?!/r?P????*eK?????@?anq???r??1????27??? [x??j6?w??b8Ss ?m?6~??z??????.?w????????k?W?p?o?LBf???? +K?O6???b???4)2^*~???y??_??????k??????? ?"a??1???P??1~?I?/?1J??p?jc???????Dk`????7? ???N?B???6??? (????VzVpV?Y?????n?lc????j?.3(????6??r?g??????????f?i? ??C?????Vj?_???Z???K????b??sD??????}??=???@???W?Z????S-%?Q???>?7n???_??C??{^?paD +#L??}?u???L?S?f?5G?????isg????j??E?$J??IS??(cj??"?A?iw??WL???( +???UmZx[p??1???????=????I??????*w_FP:? c +??>?4?? +B?D?????*?[?|7????B???d)????M??y?@4?????????V??A{x?K???Ke?A?k??????????????:?????R>? ???l??kY?$??~ ????> endobj 293 0 obj << -/Length 1203 +/Length 1194 /Filter /FlateDecode >> stream @@ -908,8 +906,8 @@ ?4?h????\ 1g?+B????X??T??T7c}?f5*????????d??|?[?~ -G?????mr}???g?c????< +???b???%?_?ICop?????B??t??i?cz???S??I ??w???g?H ??t??d?`a????????9?M??/M????????Bpwn????u;7c??????????V?y7+?1}?z???|jp??}#?P?z???U??)C???g?+????O??+??Pk??_5R+&???)??T?f??9&m??????m???LbT.??KU?oUA?=?????k??y?X?? +C? ?2???a?????] endstream endobj 292 0 obj << @@ -951,26 +949,40 @@ /ProcSet [ /PDF /Text ] >> endobj 316 0 obj << -/Length 2676 +/Length 2551 /Filter /FlateDecode >> stream -x??]s???=?B?{8z?B??????\?t?k?V??>?"d??H???????b?H3???\??~????n?/???????*^d"??x??.?? ??$?E????X??K/?????a?lTi B_??W?????q?????????C{h?(:??????E?^w?????ii??rch?c?????+)E?????,?ye~?#?????t?tF0I?P?K?L? aJ8?? ?{w???;3z?t?<??T????????6?????"K????]?????*?W7u??uY?????]j?4?{ '?|?6N4?rC?- -?b^???=??|??n?7f?????Q?5????n??@???+B\D??????????????Bz??7?c?C?>2 -???????f??=??J??{M?c??K?/?????l???q8 ??Y?a  -?^[?{?l[??????????a\y?9V?1?Q rA?V???j??d????????S??>3????? G?P$Ytr???,??.hB"??????q,?h???h?Wg"Ib?j? ??z??^?V/.q?X???? ??gc6? -)P6?X???T?~? -y???????~???][~??'?-??_??? G??u[Z??br?0??48??q??#?k??('????*?XP?Ry?Z??(V????l!???L????S?@?T6&??E?^?L??????? -I?????E$d?s??R?H??i?+????Ih+;?????E~* ?,?b?-??????$?[^7????[?)&?w?E?A?*?`?BgT?75{??f&Er??[?%]i???sf% @:?QA2????Gz=Z x?,? ??6?j-yui:}x( -??x??fU?dXv? ??????]????C??*D??rv??o?? i???? -e?z??????2?<$???!?O?(?:?D??????m??c?Z???m9???*????????p?G??oSZ??#?-??C?1????3??mS?/??4?H??8?(??!?`?i?AX???J? -?0>o?????g?}????n??kc?'?E??????[?8q6?s???B?F?|"H:?j,???n?X)???6???4R???? ???m?[????q2.????=??)???S.?7??M?+Cs?V????6UZ???????????? -??r??????J.?????_e`C?9?#?DQ5[M?S??p?5i ??5????{?????f:??????*0?.???????=c??#???6?????I?T -?*???????m?94ua????EY???*?c`???r??n???;S??c???1??)?_?~?'?xu?$??4G????}???`,D???~???A?w;????e????JX??F? ???[;??b???.?q? jh???KZ?w????fkp??vd?pW?P^X?O????GF??"?J]A?=???CpO??d}?Om ???????O?wS??li??>/?Ou>?+B4????i|.mk6?wU?fA??-?????1?5C??CQ???!(H??;?U?]??l??v????k?SH?%????a???3u??%"????g&I?Tp*?f:5???w?'Z18??????;M?+Gw!?AE?{PL?c ??e?L???!w9???9????4wm?:???Jm??????????x?o??+?_????*_??i[?U???36?"??QCa? ?G???kr? -M???+?}?W?\?qeROJ?????S????+????sQ?v?f?*???G??-?9c?)?\?U???!??H????@??gC?#M???kx??m??%?z??C?? ????W???l???NH?=???;?, ??! v#?M~i:?'?!???P?"???s????6I??z???vO?????????t?o???l??????0?q +x??YKs?6???P)??U?$>??O????l65v*??h???H +@??????nR$???N?? 4??_???_???yw???{/2??a???,?2?I? %??m????^???????h0Q???| l???|?lo?f?S??????0?Y?8r?V?ABK???b?|?????t?m +?oC?u?[K??[??{??X??TL???eq?+???????z?^?!?:?TC??t? +S????\?????;]?vt?i;92 +2!?X ?nE?????d??$Yvj??E?<?-C8vS?yY??=????O??Z???sJ?z???j??Lmi]?O#?/km??I??h??n?G?W#=+?r???s? +?"? +???]????????X?1ki??a???P???p?j?.? [w&????i4?hv??H?q'?}? vt??K?f? ?n???f????r??j?8_??;??&?.?????????c6?;M?i2??B ???3?} ??h?g??{C01??y???P?D5?c??qv?j^Us?%?A-????&?0?????k???H$?:?B?4?y^??+?<?o???W?~?2?:I?F\H9?E??H..??8?P??0??gc5? + (?z ?6'H?/GX????L=?=ts ?.oM???Ol ?? _?B?-w???M?????B?g?`???G?????l>?X?{?K?7#-?| +?.g?E"N?3????MP)?=?&X??E?f7???n???Mv?`?$????? +zf?2?%#????N?Jf??4??????lp??JBO[?J?0?11B+IR??y??a?.???f?>&?????N"?????????K4?$?n4?(4??L?? ?:cs??ih!$ ?M???VW?l???A? +??a2??H?4#?:???? ?G?R)M=?@Z???m????@X??zc?U???0?? +???@}~2?\?N6 D??>n??v?0Q??? +???Fi$? ??g?d??$???n?&?0I8?D?s?^~`r??????PH??????r??nT>?tF?????!p?????m????B??'?i/,H??F2?b5?"1)??1a> >> endobj 303 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [301.688 419.394 378.4 428.275] +/Rect [301.688 438.667 378.4 447.549] /A << /S /GoTo /D (Rfn.fitTsfm.control) >> >> endobj 304 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [277.439 401.531 354.151 412.435] +/Rect [277.439 419.978 354.151 430.882] /A << /S /GoTo /D (Rfn.fitTsfm.control) >> >> endobj 305 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [410.359 312.685 422.314 323.589] +/Rect [410.359 326.795 422.314 337.699] /A << /S /GoTo /D (Rfn.lm) >> >> endobj 306 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [263.022 288.775 289.922 299.679] +/Rect [263.022 302.885 289.922 313.789] /A << /S /GoTo /D (Rfn.lmRob) >> >> endobj 307 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [419.508 260.93 441.426 271.834] +/Rect [419.508 274.263 441.426 285.166] /A << /S /GoTo /D (Rfn.step) >> >> endobj 308 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [455.471 260.93 507.277 271.834] +/Rect [455.471 274.263 507.277 285.166] /A << /S /GoTo /D (Rfn.step.lmRob) >> >> endobj 309 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [345.052 225.064 396.858 235.968] +/Rect [345.052 238.397 396.858 249.301] /A << /S /GoTo /D (Rfn.regsubsets) >> >> endobj 310 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [117.35 189.199 194.062 200.103] +/Rect [117.35 202.531 194.062 213.435] /A << /S /GoTo /D (Rfn.fitTsfm.control) >> >> endobj 311 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [413.249 173.308 435.167 184.212] +/Rect [413.249 185.865 435.167 196.769] /A << /S /GoTo /D (Rfn.lars) >> >> endobj 312 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [264.559 121.553 311.383 132.457] +/Rect [148.882 133.332 195.706 144.236] /A << /S /GoTo /D (Rfn.fitTsfmMT) >> >> endobj 317 0 obj << /D [315 0 R /XYZ 99.346 773.487 null] >> endobj 318 0 obj << -/D [315 0 R /XYZ 100.346 694.134 null] +/D [315 0 R /XYZ 100.346 692.091 null] >> endobj 319 0 obj << -/D [315 0 R /XYZ 100.346 374.319 null] +/D [315 0 R /XYZ 100.346 389.896 null] >> endobj 314 0 obj << /Font << /F36 151 0 R /F44 189 0 R /F22 152 0 R /F35 150 0 R >> /ProcSet [ /PDF /Text ] >> endobj 333 0 obj << -/Length 2313 +/Length 2311 /Filter /FlateDecode >> stream -x??Y[o??~??X???YV?]9???$M??)l?E??A+Q^?h??D????g?C?fm??Y???\??????^????????x?*fq???|?m??^? -??????V???m???m????????q???X8 at Nm?q?3[????Ytv?F??_m?'???D&????????GV???-?? ??? -wY`?^?R?????m?I^?]?:o_?7?Y/E^7z???DIC%??[??wdUZ??0????&m?7b_??o}??DF?@?b?????>??B??|??k*??Ph?OI?Y??$p?-*E????B?h??? RY ??|??????n??N}?M?????:????c??A3????8#];`??3??V? 91??8??? 6\????}? -T4w??,??z????????Z?-*????x,?#C??nv?? -?P+4??d=p.?p?e"c??;??hGz??0?{??eY???Is????}?$U?$????? ??Yf3z????C?*u9?Mq??e??c"???|?`?"??V?9?k6??|@}+?tZWk?6?/??l?#?D???eM?8?????>?v?7?a??{???? -A??9????? ??Y4d????K??!??~O??/?^k?H??/????2?????r?K?#????v?R??]?B??? ?F0??[??v?|??@?~W????,?C?????????|??????????p:??T??\????????~Ym??'?8?Fk/?c?? ?!??A?\??h?t> ???N'?;QA?:Q??s?:??]?*/?1@??+!?E???????;{????j??=)H?E?%?R`{?=1??l?T'i?F?M?J?.dL?w?b?Eb? ????L?xx???*????H??????,+P? -FQ=1?s?'?|QZ??2l??t?x?oj?????K?T???4?uL?Rx???`???L?S???????w\??'?j:*??N?????6????\??? =p'~ -???Z??????y%???z?Gh5????Q???*??D%???h???C=??????????\W????W?I?J??W=??l???8 ??????????5??q?N?S?F?ZJ?`???A?X?BB????g~?9[o|?V???g?pj??~(Q?kh 2?6??CJ$???K??8 ?????j???Kr???Kr? ?bB=?X?~?8w}%?a=i?P??xt?>!HlK?ZQ -?~>C?'(?}1?h v^ -?a???h??Y?}oMr??VBA?4??????'????9???&???R??y???E?3?4 n~ZX?C%?6??_?'??';??tg7%?Nz@??^a???E?Gs??p??y6j????? -s???p7???1q3 ??????T?07?bT????????hg>Yu???a???I?8????g^~?*??????u????5??? -?4[?]|z??5==???uK?????MR? p?7??7??VmR??? ]???g??NT'?r-r?Z??Jg1u??????o? -?=???????? p??V??J?^???????????_?_T?c?1j\=#C????? )j?f?zo?w??I O?????????o ???I??I?w?Oi?????-5?T????A???????!A?z???m5???k???\?? -tX??wf?????n?]?$U????Rl??(????@hI??F? *?z??5????f? -? -?j'?J???JC??????????b=??????E?????A|???;?????XT?_2=? ?????`8?tC??u?8s? -???8?^?N?W???J?4C?F???:.??9ZwW?????0?R????qN???x???;AYm???VTM????r???y???? -?????6]0ZD?y????>T?????[O??8V????Qw??*??Q?j????%M??uzh?Td???'?zU Yv?????J?_?D????J??;lgO -?E8??A?h ????Co???NE??v at b??`~????/5??(?y?8?P0k?N????"T????N?u??T ???`M?m????? ?T???A??i??M?!??h?p?o????:^?>???jy5 +x??Y[o??~??X???YV?]=???8?q +?h???A????%j+R?s~?rH]??dm,???s?f8?.n????W7/~x????-n?u]??"?\???f?????u=y#?z????o?h?A?F$?< ???j? ??_????0????Op?e#?r?E????N??r?????q????y???5??f?*jNd?o_???)y????Yzy&?0???-??% +?O???$P?[zv??l??I{^??Lv-??M&3%!H????a???k?n???r?????e9?????N???????O??)?u?5j???,Z?]^? z?? $ ?=xF?????Y?H??????QnY{_ +?M}'?*??Y ?~R?d?l?????kL8?^@R7??????_?QD"?F?????U?a????????|?8?c??P? ?-KxV???????????????g?EI??v?????B?~??9?"?B????Ba???Si?????_&~?? +??]]g?8?F?fr?b? ?!M?A?]??r??Dn??7[??n?(?M??I???$???9??????T%??7???[B}U?.?IA?,7]V?v??CM?6?M??l?????C?dEg*??e ?(??O??^?LLl?C ?$H?>|u???J?F?pV=)?s?'??>k>??} ??w?D????lA?2???:?m??cS??:??'H|P???(?q??XPY????S?$? +?c3Nz?qC?>j\?=?>q?D???VK?? 2C?X0?2+???z??????F)??_SJo8?J?iu4apE?? +???|k\G_??b?XI???$MQ%???gm?R/??j?2W=?#???y?kU???????r?????j? +??|z??/?@?????c???:?? ??@?u cv??D????CV?????-?_?%F.?XJ???x????q?m?.????????8p.^?N??8???~???f???~??o?$~WM%???l????xj??]}??l5?? F??1?x?E4|?????q???bQi??pRy??"J?$[V,k??@??mI=?qe??3??l???????&?m?S?-?????y?0??Unp??my'0??0E!??^3?4?????G??.*?i?X???s>r???E???}Im8?????,????????7?B??}???)?z_????????B?_?W?!?.?????o?r;!? ????E??^???k????*?c???+?e?w4?Oa?}??Hlc{/??d??L?MO?< +c?F?(??4??Z?Is?HU????????j??i#y????.3?q?;J4??}k1?f????? ??P??T?}6s????????F endstream endobj 332 0 obj << @@ -1111,46 +1123,44 @@ /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [331.391 703.799 368.252 714.703] +/Rect [331.391 717.461 368.252 728.365] /A << /S /GoTo /D (Rfn.na.omit) >> >> endobj 334 0 obj << /D [332 0 R /XYZ 99.346 773.487 null] >> endobj 335 0 obj << -/D [332 0 R /XYZ 100.346 655.067 null] +/D [332 0 R /XYZ 100.346 668.815 null] >> endobj 336 0 obj << -/D [332 0 R /XYZ 100.346 312.511 null] +/D [332 0 R /XYZ 100.346 312.289 null] >> endobj 337 0 obj << -/D [332 0 R /XYZ 100.346 267.563 null] +/D [332 0 R /XYZ 100.346 267.382 null] >> endobj 331 0 obj << -/Font << /F44 189 0 R /F36 151 0 R /F35 150 0 R /F22 152 0 R >> +/Font << /F44 189 0 R /F36 151 0 R /F22 152 0 R /F35 150 0 R >> /ProcSet [ /PDF /Text ] >> endobj 349 0 obj << -/Length 1510 +/Length 1509 /Filter /FlateDecode >> stream -x???r?6???`???3??c??:???{I|?IH???B?????n -%?qz?x?|?{x?l? -l????????=#D?gy?re???x??a??????3?????^_8N??v ????41????2?(?T^?`-????fs??|y?X\367-?NS^ ??? ? -?F? -???)E-?O?#;p=????,?`??2&6E??& ?lU? -X???I?O?<I??7ZS?C?QJEx%?jb?wR?i!P??>}??xar???*Y?DOKsC?????%???q+???3?!?oS?WYF??g?$?a:?Fn??L??(?i?@*bk& ?t?i1????$_?#6'??A?4M?|SV?. -???lu? -????!X|H?? ^*?d?W?Yq?"????s:1??[???I?=b????????L???=?$???m?~'????Ft?0???KnK/?e!????{?????Q3;?(????g?,D?{?`?8??e?0???8???l?2>:w??C`O =??CP?????07]?giAc?TP??"SP?Y?????&??Pq?????` ]??L??????M-'????K9g?4c|i -?y~8???O2????t5<YN?#??uO2???=f?????0???~.?L??????? -??)?d?*s?~?s?zNvF??.??????UC????Q?p??I??0GR?X^????.P??d6??_6I?A?K:B?&????..N/??;'???g?eQm;?~???????Y???m?f,??58?6i% -S???h?W?"??d?'6Z???T????U?*^g Nyu??S^Z&?.X?aOb!????)p ?w??=}????????v?:e???zS????=k20???|au??ksH??????h??u????r??(??\?L?+?6?? ?_?\????Fv??W???9zu,???5 ??L<^$.??6???/'?'???}??U? -?(?|??F H -?:0????????;r?????????~` -P?s?ac??o#v?????? -?,? j?+??y?w|??-?,??]???@^?s??F^???tz???l?????{?3??^?????ra -s????q???iS?} ?? ?C???????R?-8??'???C???WH??c?1>8?s??mX????M;p??????Pm-?:? ??B}???Pgb??q{?????r?lS??X??1?????7???S.??{?"?i???`j)???lN3Fs?????`XNu?V\K/???????U?????p??/??sf?e??YDU#Y??l=?f???F4??!i??r?0@? ??fR??pAA???????E????????6?@??u?n/?N?5???????y.???-6=e#`???`?bZQ??? +????T?D=VA?3D??*S??x?????dv;Q??Yr\??0 ?/-+O?EP?;Y?L???9a?z?. +??hR???a?q`??&$~?;/?3HE?L$????.?v????lBP???VQQn?^????Nf +bSr????`?:?H??'?Q?'??L??!%????????????????B +???Z?s&???s???a??s???????>??????R*???*4?t?yGE3???M0?0????1H?? ?I?.??Y3??6r?f??T&QI &fI?7?6??g?y(???&]? D???iz?Qf??x?Yg??+3?!!??+F`????!2?P?VC??t# +s&k^ +??^??s?3j??vU??..Z?_?? +???5?6? s$g?????9?j6V?????*KV3r??%?????O&??&??Y?????????g??"?ee?U??nt??s?A?ld?#???@? z?LW??Q?f?*p,?;p??@Q????g??Ap??WF?#??P:????o2???uNd?????=?h-dv??\*????9?lm?8&?i?)? +?C??P?Y?:<??g???? ??8?/L ?? ?@???P ?P?_ +F ?$> >> endobj 328 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [328.906 709.359 390.674 720.263] +/Rect [328.906 708.926 390.674 719.83] /A << /S /GoTo /D (Rfn.predict.tsfm) >> >> endobj 329 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [393.185 709.359 444.99 720.263] +/Rect [393.185 708.926 444.99 719.83] /A << /S /GoTo /D (Rfn.print.tsfm) >> >> endobj 330 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [461.17 709.359 522.938 720.263] +/Rect [461.17 708.926 522.938 719.83] /A << /S /GoTo /D (Rfn.summary.tsfm) >> >> endobj 338 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [273.254 691.968 295.172 702.872] +/Rect [273.254 691.08 295.172 701.983] /A << /S /GoTo /D (Rfn.coef) >> >> endobj 339 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [297.683 691.968 329.563 702.872] +/Rect [297.683 691.08 329.563 701.983] /A << /S /GoTo /D (Rfn.fitted) >> >> endobj 340 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [332.074 691.968 378.898 702.872] +/Rect [332.074 691.08 378.898 701.983] /A << /S /GoTo /D (Rfn.residuals) >> >> endobj 341 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [381.409 691.968 408.308 702.872] +/Rect [381.409 691.08 408.308 701.983] /A << /S /GoTo /D (Rfn.fmCov) >> >> endobj 342 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [410.818 691.968 462.624 702.872] +/Rect [410.818 691.08 462.624 701.983] /A << /S /GoTo /D (Rfn.fmSdDecomp) >> >> endobj 343 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [465.135 691.968 521.922 702.872] +/Rect [465.135 691.08 521.922 701.983] /A << /S /GoTo /D (Rfn.fmVaRDecomp) >> >> endobj 344 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [134.227 680.496 186.033 690.917] +/Rect [134.227 679.608 186.033 690.028] /A << /S /GoTo /D (Rfn.fmEsDecomp) >> >> endobj 345 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [117.35 663.105 139.268 673.526] +/Rect [117.35 661.761 139.268 672.182] /A << /S /GoTo /D (Rfn.paFm) >> >> endobj 346 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [274.824 233.634 311.686 244.538] +/Rect [274.824 235.32 311.686 246.224] /A << /S /GoTo /D (Rfn.fitTsfm) >> >> endobj 160 0 obj << @@ -1259,55 +1269,55 @@ /D [348 0 R /XYZ 100.346 744.525 null] >> endobj 351 0 obj << -/D [348 0 R /XYZ 100.346 647.216 null] +/D [348 0 R /XYZ 100.346 644.619 null] >> endobj 320 0 obj << -/D [348 0 R /XYZ 100.346 321.928 null] +/D [348 0 R /XYZ 100.346 325.984 null] >> endobj 18 0 obj << -/D [348 0 R /XYZ 100.346 321.928 null] +/D [348 0 R /XYZ 100.346 325.984 null] >> endobj 352 0 obj << -/D [348 0 R /XYZ 100.346 268.8 null] +/D [348 0 R /XYZ 100.346 270.919 null] >> endobj 353 0 obj << -/D [348 0 R /XYZ 100.346 206.273 null] +/D [348 0 R /XYZ 100.346 206.706 null] >> endobj 347 0 obj << /Font << /F36 151 0 R /F44 189 0 R /F35 150 0 R /F22 152 0 R /F45 191 0 R >> /ProcSet [ /PDF /Text ] >> endobj 367 0 obj << -/Length 2863 +/Length 2888 /Filter /FlateDecode >> stream -x??Z???H??+?T@)? W4|????5?????JLI???$UK?Dd$WQ%?=??L%??D??xY|??????|xx?????Bz??=lf?s?o?{??J???o??9??C???????Ho?x??????}?p??f5_?C?p??u{c?v?R??G??/o_l???j????????-?D"d??D?^G/???[?=??jt??._T?(?Jj'9=?.?????.???^'???????Ms????ua'?4????_??f????????.]????e?C N???X -??.?I'??Hx??*B?(?uR?QJ?o????s?vC?fz?????????1?;? -6 |?$???}Y?ue?A?0 -']???6??$5?t?+?w?_ at x??/??P??  -?pU??-?-??? @??????3'lq??I?J5?t -!??W?U??jrq8???kT2???????p?(??5???N???????R2![?,?t=r??2Y????\?? ;M??`*? -"???????GeoP?U?xf?M?8???@E4)?D??? tTQf[Q5zgY????yY?????."?A??ahe??v????; ]? ?cj$?Cc?????????)??'MQsS?I@?qx??z?E?????du????L?*F?"???`#?bMT??U??P?:?qy???#?J?kM?Ff?,??????i?l???~c?Q?? ?e???????L?)??"!??q? ? 2?%\?N>4Xs&7X?Qa+\@??.t???(M??q/?7????`={??P-?????e?mWhb.h^n?~? /??v&?????M?^#???$??(?A$ ? -?HC??u????$?h49?#?h>??i?GY?kq -??3L8 ?l??????)??*\??hQQ??\?l??%v?Q?G??????G??v?q? M??S?fSM]???F?>}??=???e??x-$?Q?H?c?yC????H??a??.??>G?'???v??iz&??????9???Ar  ??????e?_u?c??D?P?????9-?P???m????? -???K?~?U?F -ep? -G?3Q[?> ???D???v(?@j?Ny?BN?:?Ur? -???0? -{n???cH??'?j??QOb?t8cEL?0??/?1Pl??????u ????K3??B??MD?eF{Hy? ?? *?I?? ??II??6???q?D@&????w??S??Rr}?s??5&????? -??]?t????v?|??=??????3? -??#l!??DKp??Q???p?xJL????RjP??'m?W???'?????????cG)?lo????xfIU??VM?s?Q???.?^ -?????a1.?????????'p??>?2Z_???l???f??????????T#????SI?????????N??????6???-R$USzH???S????I??????m/Y?????????%???.???|Hn???+???.??b?????(?N??:?r??~??:????#;???u?*%`Ra??p^?j????J??c????T??Zl??|U??k?[??[0Vf?&??eyX???"?DH0??????;????#b?+C ?%?s?2???h?%???ib?eHT??'p?*?ui??O?i?sqQ8"?Q-f(fnk?????["?r??p?/??E?:???r?&vg?l??[??p?1:?S?F??e???f?C???????O??Q?1>?????xC$?]?`?u at d?d??a??}????2?Z?u5|??.?? ?????????_???n{?2???^E??????V=?s??iP??%?Wor???v?a9???Ri}?A* -????JpN*.a8 lq??5xIr?Q??($??????????u1Ag??d?S[??V???-?@??m?g?K??be?|????D?C????)y5????N1N\4 -?????????T??E5??uZ -/????????(6??p$yG???4vT????S&?d??7?@i /8????K??????@??F??2???2L??>?5????????jm??6??1?-???%|??l&???!??????????5.s?+???s???r}l.5?W?J???$????+@??]?\??~???????`?&]?L??w~??4?????9?1-DzG?vsV? J,?D??SN?xC??rR%??????n ??iE????S?a??]H??{J%24?E??x?w?Pk???}????j{?W??{^?Uu?5y:qz???S?\??????C?7?Q]4?????????V%U??:????!O?t??j,?57:??l(? -R?jWkQz?b?#???????????$?w?nB????? -????'H?wFv?????BLo?^???n?d???????K?A ????jt#_??B?K?{?|s?????h?B?{E?S???E/???Z???;??K -6? 9I?$??W??'?????J?`HxGx??. 6??{??? ? +x??ZK?????WL????x?Y)l????l?b???{?DHb-2Iyf????)??F?7?)?@?????7?~??7????y71????+????iA?o??????w*?????U?~q?[C??V?x?jJ?????~z?:c? ?????uM%g??F?\z?n?@{?'?n?#??~y??????5iY????? +n???wMe???@B`?4T?k?P-u?Z?`??O???U???n$?????/???????a?i?e?n? P?n??\??f6!?Bz ???z?Cn*?Y????????g^???w]?z?V? (Dz7????4???*f^???????n?}??R ????B?w>???n???? ??a\,?EQH????@C?sW??? ??4Uw?Y??????k?A +??ql/e??N?9?N?t(??( jsk???p????*??h5??_??P?co^?U???J??lu????/?}az?j2??+?taO???? +;????????^??U?????`k????Fct?X&??2??|R?F??iU ?IM?X4?Y?eO???????H??2>~????^??kY)?+???2??,k??)_8?????`?u\`jHn?????L ??Wq?!q??? +t?????T?At???????|?????"???????4??0??"WTfw??92??c? +? +t?????V??????^GqR'?N*?:?T?? o?#&????v#1?????,????7??E??RY{'??'??X???&? ??u?????????????S?4~FC??xw??*K??b?u??*????9??l??3i?Gr?r?X7<?Dh?I?)?????1Sq4??^?????+%E??t??????^. +`1?&??]?5?0?: +?M?A??y at iP%?uJ`?zZbD?5??????c?zU???tM?? +??T@?6?j???An?ui?:O ???n?  ?+??????=???"?/k????!??m?Pa)4?! ?]LcR8?? ?()?j?j???L#?=?S0BSg?Z?5?wtZX}??|m?2????.???L5?U?bq???$???g~?^?c1P??eY?s2?X$Gf?]????i?~,??Pv???H???y?!+_???????m?z?tI4??9)??|?4?? (~?"?5DgWh?!&R?8?????*?'??x?lL?????[??O??T 5?????-???) 25?I?? X???F?*???d??P? (?????k]2??E?Jjs???Rz???I@??/??|??\]g??d?!??b??? ?([???>ct??~??z?????m?@?!4?j0??? +FEc?1???i(eo?C ???67*?|3L?`WY?Zbpe?s?H??*?IF6+? ??fM?Q'?l?y?q???QcOYg9?rPd?k0[???>??. ?L ?&??????S?41?%|? +k??F?"?4iF??!???X`??9wX???%aN4F?H???:?????? ?z???????qP?~&5/;?W????p?PeS?F???=?xY?????\?`4v?e?t??aR??nY??L(EYS;??d?$????M?w?? @?????OH????%B +???u??_??ej#?'?? $?rJ??A?a?fX?k|?<S???P????l +?K&Ol???PJ?M`3?b8????*!Hs: +????r?8?t?m??p??.??0A>~??????GF???B?s??? +l ??BJ????? l???????????t,?o?3???Q ?T????c?8?#???[@?|Y:??_ ??????#??D???2??I 2R??P?ty?MWe????)#???????6JgS?{4??.????A??0a?enj?????Q??/???5??d?x?b?3CE ?7??r??e?????(??%?6e|9?l\?I?*??q??u??@?`~?c? ?e??????|????????=?2????/?u??Q???K? +@ ??!????n???b\????TYO?-??}?`#/~? ??]cp??d??%??s??_.p?#? ?W?L7W???Kb<:?W ?????r??L??????\F?VP1xS????8?????z;Sa8G?D?>??wu!?? ?.??"?g?L??(?$???M??y??=??+*?????/ +?/=p@???r ??g?= E?TH??2?????,Dc?; +?=HjA +??r?j?????P?av/?o?U???c???????)???=?K?s?U????7? s at 3 endstream endobj 366 0 obj << @@ -1322,49 +1332,49 @@ /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [252.752 523.418 274.67 534.322] +/Rect [252.752 498.467 274.67 509.371] /A << /S /GoTo /D (Rfn.step) >> >> endobj 359 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [233.624 494.714 255.541 505.617] +/Rect [233.624 470.393 255.541 481.297] /A << /S /GoTo /D (Rfn.step) >> >> endobj 360 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [266.829 494.714 318.635 505.617] +/Rect [266.829 470.393 318.635 481.297] /A << /S /GoTo /D (Rfn.step.lmRob) >> >> endobj 361 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [440.507 437.304 462.425 448.208] +/Rect [440.507 414.246 462.425 425.15] /A << /S /GoTo /D (Rfn.step) >> >> endobj 362 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [464.935 437.304 516.741 448.208] +/Rect [464.935 414.246 516.741 425.15] /A << /S /GoTo /D (Rfn.step.lmRob) >> >> endobj 363 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [194.331 425.349 216.249 436.253] +/Rect [194.331 402.291 216.249 413.195] /A << /S /GoTo /D (Rfn.lars) >> >> endobj 364 0 obj << /Type /Annot /Subtype /Link /Border[0 0 0]/H/I/C[1 0 0] -/Rect [226.812 425.349 263.674 436.253] +/Rect [226.812 402.291 263.674 413.195] /A << /S /GoTo /D (Rfn.cv.lars) >> >> endobj 368 0 obj << @@ -1378,32 +1388,30 @@ /ProcSet [ /PDF /Text ] >> endobj 389 0 obj << -/Length 2561 +/Length 2606 /Filter /FlateDecode >> stream -x??YK??6??W?&U[???;?>L???&?????=l?@I?? - -A?=?>??$2??????x7?????(X???/~?y??]?,r?'*Y??2D%?4 D???n???T??????]]? c)?,?u??_?@?7f_?m??][?? r?W???Xc??]d?Rl?????0?>???????3???/??_?e,???B3??Q??????q?o+,uC?}??!G?a.B(????????F?"?27?o???;??=?*???X?Y1??,*[?? X??>u???A?????lz?m???f9?!)#?n??8?"????"?c??T?????@?m??zF@*??_?=?J#?s??V??v?R????bSiP????i[?B?^?W?5E}?b?3?|???r??e(?????;??x?s??V \R?? -?2?l???h}?J???N#???}???T?G??Pc%9:?a??????%? ???????!e?H??MlH`]*?NE?dS???! ??? ??H?KmNz[Uu7#?*?&??Tt;????S?????K???B?w??n?? [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3620 From noreply at r-forge.r-project.org Fri Mar 20 08:33:31 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 20 Mar 2015 08:33:31 +0100 (CET) Subject: [Returnanalytics-commits] r3621 - in pkg/FactorAnalytics: . R man Message-ID: <20150320073331.6B4B2184585@r-forge.r-project.org> Author: pragnya Date: 2015-03-20 08:33:31 +0100 (Fri, 20 Mar 2015) New Revision: 3621 Modified: pkg/FactorAnalytics/DESCRIPTION pkg/FactorAnalytics/R/plot.tsfm.r pkg/FactorAnalytics/man/plot.tsfm.Rd Log: Add actual vs fitted to plot.tsfm, edit plot titles Modified: pkg/FactorAnalytics/DESCRIPTION =================================================================== --- pkg/FactorAnalytics/DESCRIPTION 2015-03-19 23:29:04 UTC (rev 3620) +++ pkg/FactorAnalytics/DESCRIPTION 2015-03-20 07:33:31 UTC (rev 3621) @@ -1,36 +1,36 @@ -Package: factorAnalytics -Type: Package -Title: Factor Analytics -Version:2.0.14 -Date:2015-03-19 -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.15 +Date:2015-03-20 +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/plot.tsfm.r =================================================================== --- pkg/FactorAnalytics/R/plot.tsfm.r 2015-03-19 23:29:04 UTC (rev 3620) +++ pkg/FactorAnalytics/R/plot.tsfm.r 2015-03-20 07:33:31 UTC (rev 3621) @@ -1,464 +1,471 @@ -#' @title Plots from a fitted time series factor model -#' -#' @description Generic \code{plot} method for object of class \code{tsfm}. -#' Plots chosen characteristic(s) for one or more assets. -#' -#' @details -#' -#' The function can be used for group plots and individual plots. User can -#' select the type of plot either from the menu prompt (default) or directly -#' via argument \code{which}. -#' -#' In case multiple plots are needed, the menu is repeated after each plot -#' (enter 0 to exit). User can also input a numeric vector of plot options via -#' \code{which}. -#' -#' For group plots (the default), the first \code{max.show} assets are plotted. -#' -#' Setting \code{plot.single=TRUE} enables individual plots. If there is more -#' than one asset fit by \code{x}, \code{asset.name} should be specified. -#' However, if the \code{tsfm} object \code{x} only contains a single asset factor -#' model fit, plot.tsfm can infer \code{asset.name} without user input. -#' -#' CUSUM plots (individual asset plot options 10, 11 and 12) are applicable -#' only for \code{fit.method="OLS"}. -#' -#' Rolling estimates (individual asset plot option 13) is not applicable for -#' \code{variable.slection="lars"}. -#' -#' @param x an object of class \code{tsfm} produced by \code{fitTsfm}. -#' @param which a number to indicate the type of plot. If a subset of the plots -#' is required, specify a subset of the numbers 1:10 for group plots and 1:16 -#' for individual plots. If \code{which=NULL} (default), the following menu -#' appears: \cr \cr -#' For plots of a group of assets: \cr -#' 1 = Factor model coefficients: Alpha, \cr -#' 2 = Factor model coefficients: Betas, \cr -#' 3 = Actual and Fitted asset returns, \cr -#' 4 = R-squared, \cr -#' 5 = Residual Volatility,\cr -#' 6 = Factor Model Residual Correlation \cr -#' 7 = Factor Model Correlation,\cr -#' 8 = Factor Contribution to SD,\cr -#' 9 = Factor Contribution to ES,\cr -#' 10 = Factor Contribution to VaR \cr \cr -#' For individual asset plots:\cr -#' 1 = Actual and fitted returns,\cr -#' 2 = Residuals and fitted returns, \cr -#' 3 = Scale-Location plot, \cr -#' 4 = Residuals with standard error bands, \cr -#' 5 = Time series of squared residuals, \cr -#' 6 = Time series of absolute residuals,\cr -#' 7 = SACF and PACF of residuals,\cr -#' 8 = SACF and PACF of squared residuals,\cr -#' 9 = SACF and PACF of absolute residuals,\cr -#' 10 = Density estimate of residuals, \cr -#' 11 = Histogram of residuals with normal curve overlayed,\cr -#' 12 = Normal QQ-plot of residuals,\cr -#' 13 = CUSUM test-Recursive residuals,\cr -#' 14 = CUSUM test-OLS residuals,\cr -#' 15 = Recursive estimates (RE) test of OLS regression coefficients,\cr -#' 16 = Rolling estimates over a 24-period observation window -#' @param max.show maximum number of assets in a given plot. Default is 6. -#' @param plot.single logical; If \code{TRUE} plots the characteristics of an -#' individual asset's factor model. The type of plot is given by -#' \code{which}. Default is \code{FALSE}. -#' @param asset.name name of the individual asset to be plotted. Is necessary -#' if \code{x} contains multiple asset fits and \code{plot.single=TRUE}. -#' @param colorset color palette to use for all the plots. Default is -#' \code{c(1:12)}. The 1st element will be used for individual time series -#' plots or the 1st series plotted, the 2nd element for the 2nd object in the -#' plot and so on. -#' @param legend.loc places a legend into one of nine locations on the chart: -#' "bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", -#' "right", or "center". Default is "bottomright". Use \code{legend.loc=NULL} -#' to suppress the legend. -#' @param las one of {0, 1, 2, 3} to set the direction of axis labels, same as -#' in \code{plot}. Default here is 1. -#' @param VaR.method a method for computing VaR; one of "modified", "gaussian", -#' "historical" or "kernel". VaR is computed using -#' \code{\link[PerformanceAnalytics]{VaR}}. Default is "historical". -#' @param ... further arguments to be passed to other plotting functions. -#' -#' @author Eric Zivot, Sangeetha Srinivasan and Yi-An Chen -#' -#' @seealso \code{\link{fitTsfm}} and \code{\link{summary.tsfm}} for details -#' about the time series factor model fit, extractor functions and summary -#' statistics. -#' -#' \code{\link[strucchange]{efp}} for CUSUM tests. -#' -#' \code{\link[xts]{plot.xts}}, -#' \code{\link[PerformanceAnalytics]{chart.TimeSeries}}, -#' \code{\link[PerformanceAnalytics]{chart.ACFplus}}, -#' \code{\link[PerformanceAnalytics]{chart.Histogram}}, -#' \code{\link[PerformanceAnalytics]{chart.QQPlot}}, -#' \code{\link[graphics]{barplot}}, \code{\link[lattice]{barchart}} and -#' \code{\link[corrplot]{corrplot}} for plotting methods used. -#' -#' \code{\link{fmSdDecomp}}, \code{\link{fmEsDecomp}}, -#' \code{\link{fmVaRDecomp}} for factor model risk measures. -#' -#' @examples -#' -#' # load data from the database -#' data(managers) -#' fit.macro <- fitTsfm(asset.names=colnames(managers[,(1:6)]), -#' factor.names=colnames(managers[,(7:8)]), -#' rf.name="US.3m.TR", data=managers) -#' -#' # for group plots (default), user can select type from menu prompt -#' # menu is repeated to get multiple types of plots based on the same fit -#' # plot(fit.macro) -#' -#' # plot specific option(s) though which -#' # plot the factor betas of 1st 4 assets fitted above -#' plot(fit.macro, max.show=4, which=2) -#' -#' # plot factor model return correlation; angular order of the eigenvectors -#' plot(fit.macro, which=7, order="AOE", method="ellipse", tl.pos = "d") -#' -#' # for individual plots: set plot.single=TRUE; specify asset.name -#' # histogram of residuals from an individual asset's factor model fit -#' plot(fit.macro, plot.single=TRUE, asset.name="HAM1", which=8) -#' -#' @importFrom PerformanceAnalytics chart.TimeSeries chart.ACFplus -#' chart.Histogram chart.QQPlot -#' @importFrom lattice barchart panel.barchart panel.grid -#' @importFrom corrplot corrplot -#' @importFrom strucchange efp -#' @importFrom robust lmRob -#' -#' @method plot tsfm -#' @export - -plot.tsfm <- function(x, which=NULL, max.show=6, plot.single=FALSE, - asset.name, colorset=(1:12), legend.loc="topleft", las=1, - VaR.method="historical", ...) { - - which.vec <- which - which <- which[1] - - if (plot.single==TRUE) { - - if (missing(asset.name) && length(x$asset.names)>1) { - stop("Missing input: 'asset.name' is required if plot.single is TRUE and - the factor model fits multiple assets.") - } else if (length(x$asset.names)==1) { - i <- x$asset.names[1] - } else { - i <- asset.name - } - # extract info from the fitTsfm object - plotData <- merge.xts(x$data[,i], fitted(x)[,i]) - colnames(plotData) <- c("Actual","Fitted") - Residuals <- residuals(x)[,i] - plotData2 <- merge.xts(Residuals, fitted(x)[,i]) - colnames(plotData2) <- c("Residuals","Fitted") - fit <- x$asset.fit[[i]] - - # plot selection - repeat { - if (is.null(which)) { - which <- - menu(c("Actual vs fitted asset returns", - "Residuals vs fitted asset returns", - "Scale-Location plot", - "Residuals with standard error bands", - "Time series of squared residuals", - "Time series of absolute residuals", - "SACF and PACF of residuals", - "SACF and PACF of squared residuals", - "SACF and PACF of absolute residuals", - "Density Estimate of Residuals", - "Histogram of residuals with normal curve overlayed", - "Normal qq-plot of residuals", - "CUSUM test-Recursive residuals", - "CUSUM test-OLS residuals", - "Recursive estimates (RE) test of OLS regression coefficients", - "Rolling estimates over a 24-period observation window"), - title="\nMake a plot selection (or 0 to exit):") - } - - par(las=las) # default horizontal axis labels - - switch(which, - "1L" = { - ## time series plot of actual and fitted asset returns - chart.TimeSeries(plotData, main=paste("Actual and Fitted:",i), - colorset=colorset, xlab="", ylab="Asset returns", - legend.loc=legend.loc, pch=NULL, las=las, ...) - }, "2L" = { - ## residuals vs fitted asset returns - plot(fit, which=1, main=paste("Residuals vs Fitted Returns:",i), - caption=NA, sub.caption="", las=las, ...) - }, "3L" = { - ## square root of absolute residuals vs fitted asset returns - plot(fit, which=3, main=paste("Scale-Location plot:",i), - caption=NA, sub.caption="", las=las, ...) - }, "4L" = { - ## time series plot of residuals with standard error bands - chart.TimeSeries(Residuals, main=paste("Residuals:",i), - colorset=colorset, xlab="", ylab="Residuals", - lwd=2, lty="solid", las=las, ...) - abline(h=1.96*x$resid.sd[i], lwd=2, lty="dotted", col="red") - abline(h=-1.96*x$resid.sd[i], lwd=2, lty="dotted", col="red") - legend(x=legend.loc, lty=c("solid","dotted"), - col=c(colorset[1],"red"), lwd=2, - legend=c("Residuals",expression("\u00b1 1.96"*sigma))) - }, "5L" = { - ## time series plot of squared residuals - chart.TimeSeries(Residuals^2, colorset=colorset, xlab="", - ylab=" Squared Residuals", - main=paste("Squared Residuals:",i), - legend.loc=legend.loc, pch=NULL, las=las, ...) - }, "6L" = { - ## time series plot of absolute residuals - chart.TimeSeries(abs(Residuals), colorset=colorset, xlab="", - ylab="Absolute Residuals", - main=paste("Absolute Residuals:",i), - legend.loc=legend.loc, pch=NULL, las=las, ...) - }, "7L" = { - ## SACF and PACF of residuals - chart.ACFplus(Residuals, col=colorset[1], - main=paste("SACF & PACF - Residuals:",i), ...) - }, "8L" = { - ## SACF and PACF of squared residuals - chart.ACFplus(Residuals^2, col=colorset[1], ..., - main=paste("SACF & PACF - Squared residuals:",i)) - }, "9L" = { - ## SACF and PACF of absolute residuals - chart.ACFplus(abs(Residuals), col=colorset[1], ..., - main=paste("SACF & PACF - Absolute Residuals:",i)) - }, "10L" = { - ## density estimate of residuals - plot(density(Residuals), xlab="Return residuals", - colorset=colorset, main=paste("Density estimate of Residuals:",i), ...) - rug(Residuals) - }, "11L" = { - ## histogram of residuals with normal curve overlayed - methods <- c("add.density","add.normal","add.rug") - chart.Histogram(Residuals, xlab="Return residuals", - methods=methods, colorset=colorset, - main=paste("Histogram of Residuals:",i), ...) - }, "12L" = { - ## normal qq-plot of residuals - chart.QQPlot(Residuals, envelope=0.95, col=colorset, - main=paste("QQ-plot of Residuals:",i), ...) - legend(x=legend.loc, col="red", lty="dotted", lwd=1, - legend=c("0.95 confidence envelope")) - }, "13L" = { - ## Recursive CUSUM test - if (!x$fit.method=="OLS") { - stop("CUSUM analysis applicable only for 'OLS' fit.method.") - } - cusum.rec <- efp(formula(fit), type="Rec-CUSUM", data=fit$model) - plot(cusum.rec, main=paste("Recursive CUSUM test:",i), las=las, - col=colorset, ...) - }, "14L" = { - ## OLS-based CUSUM test - if (!x$fit.method=="OLS") { - stop("CUSUM analysis applicable only for 'OLS' fit.method.") - } - cusum.ols <- efp(formula(fit), type="OLS-CUSUM", data=fit$model) - plot(cusum.ols, main=paste("OLS-based CUSUM test:",i), las=las, - col=colorset, ...) - }, "15L" = { - ## Recursive estimates (RE) test of OLS regression coefficients - if (!x$fit.method=="OLS") { - stop("CUSUM analysis applicable only for 'OLS' fit.method.") - } - cusum.est <- efp(formula(fit), type="RE", data=fit$model) - plot(cusum.est, functional=NULL, col=colorset, las=0, - main=paste("RE test (Recursive estimates test):",i), ...) - }, "16L" = { - ## Rolling estimates over 24-period observation window - if (x$fit.method=="OLS") { - rollReg <- function(data.z, formula) { - coef(lm(formula, data=as.data.frame(data.z))) - } - reg.z <- zoo(fit$model, as.Date(rownames(fit$model))) - rollReg.z <- rollapply(reg.z, FUN=rollReg, formula(fit), - width=24, by.column=FALSE, align="right") - } else if (x$fit.method=="DLS") { - # get decay factor - if (as.character(x$call["decay"])=="NULL") { - decay <- 0.95 # default value for the decay factor - } else { - decay <- as.numeric(as.character(x$call["decay"])) - } - # calculate exp. decaying weights for 24-period window - w <- decay^seq(23,0,-1) - w <- w/sum(w) # weights sum to unity - rollReg.w <- function(data.z, formula, w) { - coef(lm(formula, weights=w, data=as.data.frame(data.z))) - } - reg.z <- zoo(fit$model[-length(fit$model)], - as.Date(rownames(fit$model))) - rollReg.z <- rollapply(reg.z, FUN=rollReg.w, formula(fit), w, - width=24, by.column=FALSE, align="right") - } else if (x$fit.method=="Robust") { - rollReg.Rob <- function(data.z, formula) { - coef(lmRob(formula=formula, data=as.data.frame(data.z))) - } - reg.z <- zoo(fit$model, as.Date(rownames(fit$model))) - rollReg.z <- rollapply(reg.z, width=24, FUN=rollReg.Rob, - formula(fit), by.column=FALSE, - align="right") - } else if (is.null(x$fit.method)) { - stop("Rolling estimates is not available for 'lars' fits.") - } - par(las=0) - plot(rollReg.z, ..., las=las, - main=paste("Rolling estimates (24-period obs window):",i)) - par(las=las) - }, - invisible() - ) - # repeat menu if user didn't choose to exit from the plot options - if (which==0 || length(which.vec)==1) {break} - if (length(which.vec)>1) { - which.vec <- which.vec[-1] - which <- which.vec[1] - par(ask=TRUE) - } else {which=NULL} - } - } else { # start of group asset plots - - # plot selection - repeat { - if (is.null(which)) { - which <- - menu(c("Factor model coefficients: Alpha", - "Factor model coefficients: Betas", - "Actual and Fitted asset returns", - "R-squared", - "Residual Volatility", - "Factor Model Residual Correlation", - "Factor Model Return Correlation", - "Factor Contribution to SD", - "Factor Contribution to ES", - "Factor Contribution to VaR"), - title="\nMake a plot selection (or 0 to exit):") - } - - par(las=las) # default horizontal axis labels - - switch(which, - "1L" = { - ## Factor model coefficients: Alpha - barplot(coef(x)[,1], main="Factor model Alpha (Intercept)", - names.arg=rownames(coef(x)), col="darkblue", las=las, - horiz=TRUE, ...) - abline(v=0, lwd=1, lty=1, col=1) - }, - "2L" = { - ## Factor model coefficients: Betas - k <- ncol(coef(x))-1 - if (k > max.show) { - cat(paste("Displaying only the first", max.show,"factor betas, as the number of factors > 'max.show' =", max.show)) - k <- max.show - } - par(mfrow=c(ceiling(k/2),2)) - for (i in 2:(k+1)) { - main=paste(colnames(coef(x))[i], "factor Betas") - barplot(coef(x)[,i], main=main, names.arg=rownames(coef(x)), - col="darkblue", las=las, horiz=TRUE, ...) - abline(v=0, lwd=1, lty=1, col=1) - } - par(mfrow=c(1,1)) - }, - "3L" = { - ## Actual and Fitted asset returns - n <- length(x$asset.names) - if (n > max.show) { - cat(paste("Displaying only the first", max.show, "assets, since the number of assets > 'max.show'")) - n <- max.show - } - par(mfrow=c(ceiling(n/2),2)) - for (i in 1:n) { - plotData <- merge.xts(x$data[,i], fitted(x)[,i]) - colnames(plotData) <- c("Actual","Fitted") - main <- paste("Actual vs Fitted:", x$asset.names[i]) - chart.TimeSeries(plotData, colorset=colorset, main=main, - xlab="", ylab="Asset returns", - legend.loc=legend.loc, pch=NULL, las=las,...) - } - par(mfrow=c(1,1)) - }, - "4L" ={ - ## R-squared - plot( - barchart(x$r2, main="R-squared values", xlab="", - col="darkblue", ...) - ) - }, - "5L" = { - ## Residual Volatility - plot( - barchart(x$resid.sd, main="Residual volatility", xlab="", - col="darkblue", ...) - ) - }, - "6L" = { - ## Factor Model Residual Correlation - cor.resid <- cor(residuals(x), use="pairwise.complete.obs") - corrplot(cor.resid, ...) - # mtext("pairwise complete obs", line=0.5) - }, - "7L" = { - ## Factor Model Return Correlation - cor.fm <- cov2cor(fmCov(x)) - corrplot(cor.fm, ...) - # mtext("pairwise complete obs", line=0.5) - }, - "8L" = { - ## Factor Percentage Contribution to SD - pcSd.fm <- fmSdDecomp(x)$pcSd - plot( - barchart(pcSd.fm, main="Factor % Contribution to SD", xlab="", - auto.key=list(space="bottom",columns=3, - points=FALSE,rectangles=TRUE), - par.settings=list(superpose.polygon=list(col=colorset)), - panel=function(...){panel.grid(h=0, v=-1); - panel.barchart(...)}, ...) - ) - }, - "9L"={ - ## Factor Percentage Contribution to ES - pcES.fm <- fmEsDecomp(x, method=VaR.method)$pcES - plot( - barchart(pcES.fm, main="Factor % Contribution to ES", xlab="", - auto.key=list(space="bottom",columns=3, - points=FALSE,rectangles=TRUE), - par.settings=list(superpose.polygon=list(col=colorset)), - panel=function(...){panel.grid(h=0, v=-1); - panel.barchart(...)}, ...) - ) - }, - "10L" ={ - ## Factor Percentage Contribution to VaR - pcVaR.fm <- fmVaRDecomp(x, method=VaR.method)$pcVaR - plot( - barchart(pcVaR.fm, main="Factor % Contribution to VaR", - xlab="", auto.key=list(space="bottom",columns=3, - points=FALSE,rectangles=TRUE), - par.settings=list(superpose.polygon=list(col=colorset)), - panel=function(...){panel.grid(h=0, v=-1); - panel.barchart(...)}, ...) - ) - }, - invisible() - ) - # repeat menu if user didn't choose to exit from the plot options - if (which==0 || length(which.vec)==1) {break} - if (length(which.vec)>1) { - which.vec <- which.vec[-1] - which <- which.vec[1] - par(ask=TRUE) - } else {which=NULL} - } - } # end of group plots - # turn par(ask=T) back - par(ask=FALSE) -} +#' @title Plots from a fitted time series factor model +#' +#' @description Generic \code{plot} method for object of class \code{tsfm}. +#' Plots chosen characteristic(s) for one or more assets. +#' +#' @details +#' +#' The function can be used for group plots and individual plots. User can +#' select the type of plot either from the menu prompt (default) or directly +#' via argument \code{which}. +#' +#' In case multiple plots are needed, the menu is repeated after each plot +#' (enter 0 to exit). User can also input a numeric vector of plot options via +#' \code{which}. +#' +#' For group plots (the default), the first \code{max.show} assets are plotted. +#' +#' Setting \code{plot.single=TRUE} enables individual plots. If there is more +#' than one asset fit by \code{x}, \code{asset.name} should be specified. +#' In case the \code{tsfm} object \code{x} contains only a single asset fit, +#' plot.tsfm can infer \code{asset.name} without user input. +#' +#' CUSUM plots (individual asset plot options 14, 15 and 16) are applicable +#' only for \code{fit.method="OLS"}. +#' +#' Rolling estimates (individual asset plot option 17) is not applicable for +#' \code{variable.slection="lars"}. +#' +#' @param x an object of class \code{tsfm} produced by \code{fitTsfm}. +#' @param which a number to indicate the type of plot. If a subset of the plots +#' is required, specify a subset of the numbers 1:10 for group plots and 1:16 +#' for individual plots. If \code{which=NULL} (default), the following menu +#' appears: \cr \cr +#' For plots of a group of assets: \cr +#' 1 = Factor model coefficients: Alpha, \cr +#' 2 = Factor model coefficients: Betas, \cr +#' 3 = Actual and Fitted asset returns, \cr +#' 4 = R-squared, \cr +#' 5 = Residual Volatility,\cr +#' 6 = Factor Model Residual Correlation \cr +#' 7 = Factor Model Correlation,\cr +#' 8 = Factor Contribution to SD,\cr +#' 9 = Factor Contribution to ES,\cr +#' 10 = Factor Contribution to VaR \cr \cr +#' For individual asset plots:\cr +#' 1 = Actual and fitted returns,\cr +#' 2 = Actual vs fitted asset returns,\cr +#' 3 = Residuals and fitted returns, \cr +#' 4 = Sqrt. of Std. Residuals vs Fitted, \cr +#' 5 = Residuals with standard error bands, \cr +#' 6 = Time series of squared residuals, \cr +#' 7 = Time series of absolute residuals,\cr +#' 8 = SACF and PACF of residuals,\cr +#' 9 = SACF and PACF of squared residuals,\cr +#' 10 = SACF and PACF of absolute residuals,\cr +#' 11 = Density estimate of residuals, \cr +#' 12 = Histogram of residuals with normal curve overlayed,\cr +#' 13 = Normal QQ-plot of residuals,\cr +#' 14 = CUSUM test-Recursive residuals,\cr +#' 15 = CUSUM test-OLS residuals,\cr +#' 16 = Recursive estimates (RE) test of OLS regression coefficients,\cr +#' 17 = Rolling estimates over a 24-period observation window +#' @param max.show maximum number of assets in a given plot. Default is 6. +#' @param plot.single logical; If \code{TRUE} plots the characteristics of an +#' individual asset's factor model. The type of plot is given by +#' \code{which}. Default is \code{FALSE}. +#' @param asset.name name of the individual asset to be plotted. Is necessary +#' if \code{x} contains multiple asset fits and \code{plot.single=TRUE}. +#' @param colorset color palette to use for all the plots. Default is +#' \code{c(1:12)}. The 1st element will be used for individual time series +#' plots or the 1st series plotted, the 2nd element for the 2nd object in the +#' plot and so on. +#' @param legend.loc places a legend into one of nine locations on the chart: +#' "bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", +#' "right", or "center". Default is "bottomright". Use \code{legend.loc=NULL} +#' to suppress the legend. +#' @param las one of {0, 1, 2, 3} to set the direction of axis labels, same as +#' in \code{plot}. Default here is 1. +#' @param VaR.method a method for computing VaR; one of "modified", "gaussian", +#' "historical" or "kernel". VaR is computed using +#' \code{\link[PerformanceAnalytics]{VaR}}. Default is "historical". +#' @param ... further arguments to be passed to other plotting functions. +#' +#' @author Eric Zivot, Sangeetha Srinivasan and Yi-An Chen +#' +#' @seealso \code{\link{fitTsfm}} and \code{\link{summary.tsfm}} for details +#' about the time series factor model fit, extractor functions and summary +#' statistics. +#' +#' \code{\link[strucchange]{efp}} for CUSUM tests. +#' +#' \code{\link[xts]{plot.xts}}, +#' \code{\link[PerformanceAnalytics]{chart.TimeSeries}}, +#' \code{\link[PerformanceAnalytics]{chart.ACFplus}}, +#' \code{\link[PerformanceAnalytics]{chart.Histogram}}, +#' \code{\link[PerformanceAnalytics]{chart.QQPlot}}, +#' \code{\link[graphics]{barplot}}, \code{\link[lattice]{barchart}} and +#' \code{\link[corrplot]{corrplot}} for plotting methods used. +#' +#' \code{\link{fmSdDecomp}}, \code{\link{fmEsDecomp}}, +#' \code{\link{fmVaRDecomp}} for factor model risk measures. +#' +#' @examples +#' +#' # load data from the database +#' data(managers) +#' fit.macro <- fitTsfm(asset.names=colnames(managers[,(1:6)]), +#' factor.names=colnames(managers[,(7:8)]), +#' rf.name="US.3m.TR", data=managers) +#' +#' # for group plots (default), user can select type from menu prompt +#' # menu is repeated to get multiple types of plots based on the same fit +#' # plot(fit.macro) +#' +#' # plot specific option(s) though which +#' # plot the factor betas of 1st 4 assets fitted above +#' plot(fit.macro, max.show=4, which=2) +#' +#' # plot factor model return correlation; angular order of the eigenvectors +#' plot(fit.macro, which=7, order="AOE", method="ellipse", tl.pos = "d") +#' +#' # for individual plots: set plot.single=TRUE; specify asset.name +#' # histogram of residuals from an individual asset's factor model fit +#' plot(fit.macro, plot.single=TRUE, asset.name="HAM1", which=8) +#' +#' @importFrom PerformanceAnalytics chart.TimeSeries chart.ACFplus +#' chart.Histogram chart.QQPlot +#' @importFrom lattice barchart panel.barchart panel.grid +#' @importFrom corrplot corrplot +#' @importFrom strucchange efp +#' @importFrom robust lmRob +#' +#' @method plot tsfm +#' @export + +plot.tsfm <- function(x, which=NULL, max.show=6, plot.single=FALSE, + asset.name, colorset=(1:12), legend.loc="topleft", las=1, + VaR.method="historical", ...) { + + which.vec <- which + which <- which[1] + + if (plot.single==TRUE) { + + if (missing(asset.name) && length(x$asset.names)>1) { + stop("Missing input: 'asset.name' is required if plot.single is TRUE and + the factor model fits multiple assets.") + } else if (length(x$asset.names)==1) { + i <- x$asset.names[1] + } else { + i <- asset.name + } + # extract info from the fitTsfm object + plotData <- merge.xts(x$data[,i], fitted(x)[,i]) + colnames(plotData) <- c("Actual","Fitted") + Residuals <- residuals(x)[,i] + plotData2 <- merge.xts(Residuals, fitted(x)[,i]) + colnames(plotData2) <- c("Residuals","Fitted") + fit <- x$asset.fit[[i]] + + # plot selection + repeat { + if (is.null(which)) { + which <- + menu(c("Actual and fitted asset returns", + "Actual vs fitted asset returns", + "Residuals and fitted asset returns", + "Sqrt. of Std. Residuals vs Fitted", + "Residuals with standard error bands", + "Time series of squared residuals", + "Time series of absolute residuals", + "SACF and PACF of residuals", + "SACF and PACF of squared residuals", + "SACF and PACF of absolute residuals", + "Density Estimate of Residuals", + "Histogram of residuals with normal curve overlayed", + "Normal qq-plot of residuals", + "CUSUM test-Recursive residuals", + "CUSUM test-OLS residuals", + "Recursive estimates (RE) test of OLS regression coefficients", [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3621 From noreply at r-forge.r-project.org Fri Mar 20 09:48:00 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 20 Mar 2015 09:48:00 +0100 (CET) Subject: [Returnanalytics-commits] r3622 - in pkg/FactorAnalytics: . R man tests vignettes Message-ID: <20150320084800.AFFE71878F0@r-forge.r-project.org> Author: pragnya Date: 2015-03-20 09:48:00 +0100 (Fri, 20 Mar 2015) New Revision: 3622 Added: pkg/FactorAnalytics/tests/FactorAnalytics.pdf Removed: pkg/FactorAnalytics/tests/factorAnalytics.pdf Modified: pkg/FactorAnalytics/DESCRIPTION pkg/FactorAnalytics/R/fitSfm.R pkg/FactorAnalytics/R/fitTsfm.R pkg/FactorAnalytics/R/fitTsfm.control.R pkg/FactorAnalytics/R/fitTsfmLagBeta.r pkg/FactorAnalytics/R/fitTsfmMT.r pkg/FactorAnalytics/R/fitTsfmUpDn.r pkg/FactorAnalytics/R/plot.sfm.r pkg/FactorAnalytics/R/plot.tsfm.r pkg/FactorAnalytics/R/plot.tsfmUpDn.r pkg/FactorAnalytics/R/predict.tsfm.r pkg/FactorAnalytics/R/predict.tsfmUpDn.r pkg/FactorAnalytics/R/print.pafm.r pkg/FactorAnalytics/R/print.tsfmUpDn.r pkg/FactorAnalytics/R/summary.pafm.r pkg/FactorAnalytics/R/summary.tsfm.r pkg/FactorAnalytics/R/summary.tsfmUpDn.r pkg/FactorAnalytics/man/CornishFisher.Rd pkg/FactorAnalytics/man/fitSfm.Rd pkg/FactorAnalytics/man/fitTsfm.Rd pkg/FactorAnalytics/man/fitTsfm.control.Rd pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd pkg/FactorAnalytics/man/fitTsfmMT.Rd pkg/FactorAnalytics/man/fitTsfmUpDn.Rd pkg/FactorAnalytics/man/fmCov.Rd pkg/FactorAnalytics/man/fmEsDecomp.Rd pkg/FactorAnalytics/man/fmSdDecomp.Rd pkg/FactorAnalytics/man/fmVaRDecomp.Rd pkg/FactorAnalytics/man/paFm.Rd pkg/FactorAnalytics/man/plot.pafm.Rd pkg/FactorAnalytics/man/plot.sfm.Rd pkg/FactorAnalytics/man/plot.tsfm.Rd pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd pkg/FactorAnalytics/man/predict.sfm.Rd pkg/FactorAnalytics/man/predict.tsfm.Rd pkg/FactorAnalytics/man/predict.tsfmUpDn.Rd pkg/FactorAnalytics/man/print.pafm.Rd pkg/FactorAnalytics/man/print.sfm.Rd pkg/FactorAnalytics/man/print.tsfm.Rd pkg/FactorAnalytics/man/print.tsfmUpDn.Rd pkg/FactorAnalytics/man/summary.pafm.Rd pkg/FactorAnalytics/man/summary.sfm.Rd pkg/FactorAnalytics/man/summary.tsfm.Rd pkg/FactorAnalytics/man/summary.tsfmUpDn.Rd pkg/FactorAnalytics/vignettes/fitTsfm_vignette.R pkg/FactorAnalytics/vignettes/fitTsfm_vignette.Rnw pkg/FactorAnalytics/vignettes/fitTsfm_vignette.pdf Log: Change OLS to LS. Fix CMD check warnings in fitTsfmUpDn Modified: pkg/FactorAnalytics/DESCRIPTION =================================================================== --- pkg/FactorAnalytics/DESCRIPTION 2015-03-20 07:33:31 UTC (rev 3621) +++ pkg/FactorAnalytics/DESCRIPTION 2015-03-20 08:48:00 UTC (rev 3622) @@ -1,8 +1,8 @@ Package: factorAnalytics Type: Package Title: Factor Analytics -Version:2.0.15 -Date:2015-03-20 +Version:2.0.16 +Date:2015-03-21 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 Modified: pkg/FactorAnalytics/R/fitSfm.R =================================================================== --- pkg/FactorAnalytics/R/fitSfm.R 2015-03-20 07:33:31 UTC (rev 3621) +++ pkg/FactorAnalytics/R/fitSfm.R 2015-03-20 08:48:00 UTC (rev 3622) @@ -69,7 +69,7 @@ #' An object of class \code{"sfm"} is a list containing the following #' components: #' \item{asset.fit}{fitted object of class \code{"mlm"} or \code{"lm"} from the -#' time-series OLS regression of asset returns on estimated factors.} +#' time-series LS regression of asset returns on estimated factors.} #' \item{k}{number of factors; as input or determined by "ck" or "bn" methods.} #' \item{factors}{T x K xts object of estimated factor realizations.} #' \item{loadings}{N x K matrix of factor loadings estimated by @@ -77,7 +77,7 @@ #' \item{alpha}{length-N vector of estimated alphas.} #' \item{r2}{length-N vector of R-squared values.} #' \item{resid.sd}{length-N vector of residual standard deviations.} -#' \item{residuals}{T x N xts object of residuals from the OLS regression.} +#' \item{residuals}{T x N xts object of residuals from the LS regression.} #' \item{Omega}{N x N return covariance matrix estimated by the factor model.} #' \item{eigen}{length-N (or length-T for APCA) vector of eigenvalues of the #' sample covariance matrix.} @@ -255,7 +255,7 @@ # invert 1st principal component if most values are negative if (median(f[,1]) < 0) {f[,1] <- -f[,1]} - # OLS time series regression to get B: NxK matrix of factor loadings + # LS time series regression to get B: NxK matrix of factor loadings f <- xts(f, index(R.xts)) asset.fit <- lm(R.xts ~ f, ...) B <- t(coef(asset.fit)[-1, , drop=FALSE]) @@ -308,7 +308,7 @@ # invert 1st principal component if most values are negative if (median(f[,1]) < 0) {f[,1] <- -f[,1]} - # OLS time series regression to get B: NxK matrix of factor loadings + # LS time series regression to get B: NxK matrix of factor loadings asset.fit <- lm(R.xts ~ f, ...) B <- t(coef(asset.fit)[-1, , drop=FALSE]) alpha <- coef(asset.fit)[1,] Modified: pkg/FactorAnalytics/R/fitTsfm.R =================================================================== --- pkg/FactorAnalytics/R/fitTsfm.R 2015-03-20 07:33:31 UTC (rev 3621) +++ pkg/FactorAnalytics/R/fitTsfm.R 2015-03-20 08:48:00 UTC (rev 3622) @@ -2,7 +2,7 @@ #' #' @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 +#' Users can choose between ordinary least squares-LS, 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. @@ -12,7 +12,7 @@ #' 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 +#' Estimation method "LS" 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}}). @@ -61,8 +61,8 @@ #' @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 fit.method the estimation method, one of "LS", "DLS" or "Robust". +#' See details. Default is "LS". #' @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. @@ -82,7 +82,7 @@ #' 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 +#' class \code{lm} if \code{fit.method="LS" or "DLS"}, class \code{lmRob} if #' the \code{fit.method="Robust"}, or class \code{lars} if #' \code{variable.selection="lars"}.} #' \item{alpha}{length-N vector of estimated alphas.} @@ -165,7 +165,7 @@ #' @export fitTsfm <- function(asset.names, factor.names, mkt.name=NULL, rf.name=NULL, - data=data, fit.method=c("OLS","DLS","Robust"), + data=data, fit.method=c("LS","DLS","Robust"), variable.selection=c("none","stepwise","subsets","lars"), control=fitTsfm.control(...), ...) { @@ -174,8 +174,8 @@ # 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'") + if (!(fit.method %in% c("LS","DLS","Robust"))) { + stop("Invalid argument: fit.method must be 'LS', 'DLS' or 'Robust'") } variable.selection = variable.selection[1] if (!(variable.selection %in% c("none","stepwise","subsets","lars"))) { @@ -294,7 +294,7 @@ fm.formula <- as.formula(paste(i," ~ .")) # fit based on time series regression method chosen - if (fit.method == "OLS") { + if (fit.method == "LS") { 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) @@ -324,7 +324,7 @@ fm.formula <- as.formula(paste(i," ~ .")) # fit based on time series regression method chosen - if (fit.method == "OLS") { + if (fit.method == "LS") { 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") { @@ -377,7 +377,7 @@ reg.xts <- na.omit(dat.xts[,c(i,names.sub)]) # fit based on time series regression method chosen - if (fit.method == "OLS") { + if (fit.method == "LS") { 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) Modified: pkg/FactorAnalytics/R/fitTsfm.control.R =================================================================== --- pkg/FactorAnalytics/R/fitTsfm.control.R 2015-03-20 07:33:31 UTC (rev 3621) +++ pkg/FactorAnalytics/R/fitTsfm.control.R 2015-03-20 08:48:00 UTC (rev 3622) @@ -17,7 +17,7 @@ #' The scalar \code{decay} is used by \code{\link{fitTsfm}} to compute #' exponentially decaying weights for \code{fit.method="DLS"}. Alternately, one #' can directly specify \code{weights}, a weights vector, to be used with -#' "OLS" or "Robust". Especially when fitting multiple assets, care should be +#' "LS" or "Robust". Especially when fitting multiple assets, care should be #' taken to ensure that the length of the weights vector matches the number of #' observations (excluding cases ignored due to NAs). #' @@ -31,13 +31,13 @@ #' @param decay a scalar in (0, 1] to specify the decay factor for "DLS". #' Default is 0.95. #' @param weights an optional vector of weights to be used in the fitting -#' process for \code{fit.method="OLS","Robust"}, or +#' process for \code{fit.method="LS","Robust"}, or #' \code{variable.selection="subsets"}. Should be \code{NULL} or a numeric #' vector. The length of \code{weights} must be the same as the number of #' observations. The weights must be nonnegative and it is strongly #' recommended that they be strictly positive. #' @param model,x,y,qr logicals passed to \code{lm} for -#' \code{fit.method="OLS"}. If \code{TRUE} the corresponding components of the +#' \code{fit.method="LS"}. If \code{TRUE} the corresponding components of the #' fit (the model frame, the model matrix, the response, the QR decomposition) #' are returned. #' @param nrep the number of random subsamples to be drawn for Modified: pkg/FactorAnalytics/R/fitTsfmLagBeta.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmLagBeta.r 2015-03-20 07:33:31 UTC (rev 3621) +++ pkg/FactorAnalytics/R/fitTsfmLagBeta.r 2015-03-20 08:48:00 UTC (rev 3622) @@ -1,110 +1,110 @@ -#' @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 like \code{fitTsfm}.An object of class -#' \code{"tsfm"} is returned. -#' -#' @details -#' The lagged returns model estimates lagged market Beta. Specifically, -#' \deqn{r_t = \alpha + \beta_0 MKT_t + \beta_1 MKT_t-1 + \ldots + \beta_K MKT_t-K + \epsilon_t, t=1 \ldots T} -#' where \eqn{r_t} is the asset returns, and MKT is the market factor. It is usually -#' needed for illiquid securities with stale prices. One can also report the sum of -#' the lagged Betas: -#' \deqn{\beta = \beta_0 + \beta_1 + \ldots + \beta_K } -#' -#' @param asset.names vector containing names of assets, whose returns or -#' excess returns are the dependent variable. -#' @param mkt.name name of the column for market returns. 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 the market factor (in -#' \code{mkt.name}).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 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 \code{fitTsfmLagBeta} also returns an object of class \code{"tsfm"} like -#' \code{fitTsfm}. The generic function such as \code{print}, \code{plot}, \code{predict} -#' and \code{summary} methods exist. Also, the generic accessor functions \code{coef}, -#' \code{fitted}, \code{residuals} and \code{fmCov} can be applied as well. -#' -#' 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"}.} -#' \item{alpha}{length-N vector of estimated alphas.} -#' \item{beta}{N x (L+1) matrix of estimated betas.} -#' \item{r2}{length-N vector of R-squared values.} -#' \item{resid.sd}{length-N vector of residual standard deviations.} -#' \item{call}{the matched function call.} -#' \item{data}{xts data object containing the assets and factors.} -#' \item{asset.names}{asset.names as input.} -#' \item{fit.method}{fit.method as input.} -#' Where N is the number of assets, L is the number of lagged market Betas and T is the -#' number of time periods. -#' -#' @author Yi-An Chen. -#' -#' @references -#' Scholes, M. and Williams, J. T. (1977). Estimating betas from non-synchronous -#' data, Journal of Financial Economics, vol. 5, 1977, pp. 309-327 -#' -#' @seealso -#' The original time series function \code{\link{fitTsfm}} and its generic functions -#' application. -#' -#' @examples -#' # load data from the database -#' data(managers) -#' -#' # example: A lagged Beetas model with OLS 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, mkt.name, rf.name=NULL, - data=data, fit.method=c("OLS","DLS","Robust"),LagBeta=1, - control=fitTsfm.control(...),...) { - - if (is.null(mkt.name)) { - stop("Missing argument: mkt.name has to be specified for lagged Betas 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 - factor.names = mkt.name - 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="none",control=control) - - return(fit) +#' @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-LS, discounted least +#' squares-DLS (or) robust regression like \code{fitTsfm}.An object of class +#' \code{"tsfm"} is returned. +#' +#' @details +#' The lagged returns model estimates lagged market Beta. Specifically, +#' \deqn{r_t = \alpha + \beta_0 MKT_t + \beta_1 MKT_t-1 + \ldots + \beta_K MKT_t-K + \epsilon_t, t=1 \ldots T} +#' where \eqn{r_t} is the asset returns, and MKT is the market factor. It is usually +#' needed for illiquid securities with stale prices. One can also report the sum of +#' the lagged Betas: +#' \deqn{\beta = \beta_0 + \beta_1 + \ldots + \beta_K } +#' +#' @param asset.names vector containing names of assets, whose returns or +#' excess returns are the dependent variable. +#' @param mkt.name name of the column for market returns. 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 the market factor (in +#' \code{mkt.name}).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 "LS", "DLS" or "Robust". +#' See details. Default is "LS". +#' @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 \code{fitTsfmLagBeta} also returns an object of class \code{"tsfm"} like +#' \code{fitTsfm}. The generic function such as \code{print}, \code{plot}, \code{predict} +#' and \code{summary} methods exist. Also, the generic accessor functions \code{coef}, +#' \code{fitted}, \code{residuals} and \code{fmCov} can be applied as well. +#' +#' 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="LS" or "DLS"}, class \code{lmRob} if +#' the \code{fit.method="Robust"}.} +#' \item{alpha}{length-N vector of estimated alphas.} +#' \item{beta}{N x (L+1) matrix of estimated betas.} +#' \item{r2}{length-N vector of R-squared values.} +#' \item{resid.sd}{length-N vector of residual standard deviations.} +#' \item{call}{the matched function call.} +#' \item{data}{xts data object containing the assets and factors.} +#' \item{asset.names}{asset.names as input.} +#' \item{fit.method}{fit.method as input.} +#' Where N is the number of assets, L is the number of lagged market Betas and T is the +#' number of time periods. +#' +#' @author Yi-An Chen. +#' +#' @references +#' Scholes, M. and Williams, J. T. (1977). Estimating betas from non-synchronous +#' data, Journal of Financial Economics, vol. 5, 1977, pp. 309-327 +#' +#' @seealso +#' The original time series function \code{\link{fitTsfm}} and its generic functions +#' application. +#' +#' @examples +#' # load data from the database +#' data(managers) +#' +#' # example: A lagged Beetas model with LS 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, mkt.name, rf.name=NULL, + data=data, fit.method=c("LS","DLS","Robust"),LagBeta=1, + control=fitTsfm.control(...),...) { + + if (is.null(mkt.name)) { + stop("Missing argument: mkt.name has to be specified for lagged Betas 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 + factor.names = mkt.name + 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="none",control=control) + + return(fit) } \ No newline at end of file Modified: pkg/FactorAnalytics/R/fitTsfmMT.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmMT.r 2015-03-20 07:33:31 UTC (rev 3621) +++ pkg/FactorAnalytics/R/fitTsfmMT.r 2015-03-20 08:48:00 UTC (rev 3622) @@ -1,126 +1,126 @@ -#' @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. An object of class -#' \code{"tsfm"} is returned. -#' -#' @details -#' The 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. -#' -#' -#' -#' @param asset.names vector containing names of assets, whose returns or -#' excess returns are the dependent variable. -#' @param mkt.name name of the column for market returns; 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 the market factor (in -#' \code{mkt.name}).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 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 \code{fitTsfmMT} also returns an object of class \code{"tsfm"} like -#' \code{fitTsfm}. The generic function such as \code{print}, \code{plot}, \code{predict} -#' and \code{summary} methods exist. Also, the generic accessor functions \code{coef}, -#' \code{fitted}, \code{residuals} and \code{fmCov} can be applied as well. -#' -#' 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"}.} -#' \item{alpha}{length-N vector of estimated alphas.} -#' \item{beta}{N x 2 matrix of estimated betas.} -#' \item{r2}{length-N vector of R-squared values.} -#' \item{resid.sd}{length-N vector of residual standard deviations.} -#' \item{call}{the matched function call.} -#' \item{data}{xts data object containing the assets and factors.} -#' \item{asset.names}{asset.names as input.} -#' \item{fit.method}{fit.method as input.} -#' Where N is the number of assets and T is the -#' number of time periods. -#' -#' @author Yi-An Chen. -#' -#' @references -#' 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. -#' -#' #' Christopherson, J. A., Carino, D. R., & Ferson, W. E. (2009). Portfolio -#' performance measurement and benchmarking. McGraw Hill Professional. pp.127-133 -#' -#' @seealso -#' The original time series function \code{\link{fitTsfm}} and its generic functions -#' application. -#' -#' @examples -#' # load data from the database -#' data(managers) -#' -#' # 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) -#' -#' @importFrom PerformanceAnalytics checkData -#' @importFrom robust lmRob step.lmRob -#' @importFrom leaps regsubsets -#' @importFrom lars lars cv.lars -#' -#' @export - -fitTsfmMT <- function(asset.names,mkt.name, rf.name=NULL, - data=data, fit.method=c("OLS","DLS","Robust"), - control=fitTsfm.control(...),...) { - if (is.null(mkt.name)){ - stop("Missing argument: mkt.name has to be specified for market timing model.") - } - - # 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[,mkt.name]) - ### 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)))) - } - - # mkt-timing factors: down.market=max(0,Rf-Rm), market.sqd=(Rm-Rf)^2 - - 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" - factor.names <- c(mkt.name,"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") -# } - - fit.Timing <- fitTsfm(asset.names=asset.names,factor.names=factor.names,rf.name=NULL, - data=dat.xts,fit.method=fit.method,variable.selection="none",control=control) - -return(fit.Timing) -} +#' @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-LS, discounted least +#' squares-DLS (or) robust regression. An object of class +#' \code{"tsfm"} is returned. +#' +#' @details +#' The 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. +#' +#' +#' +#' @param asset.names vector containing names of assets, whose returns or +#' excess returns are the dependent variable. +#' @param mkt.name name of the column for market returns; 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 the market factor (in +#' \code{mkt.name}).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 "LS", "DLS" or "Robust". +#' See details. Default is "LS". +#' @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 \code{fitTsfmMT} also returns an object of class \code{"tsfm"} like +#' \code{fitTsfm}. The generic function such as \code{print}, \code{plot}, \code{predict} +#' and \code{summary} methods exist. Also, the generic accessor functions \code{coef}, +#' \code{fitted}, \code{residuals} and \code{fmCov} can be applied as well. +#' +#' 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="LS" or "DLS"}, class \code{lmRob} if +#' the \code{fit.method="Robust"}.} +#' \item{alpha}{length-N vector of estimated alphas.} +#' \item{beta}{N x 2 matrix of estimated betas.} +#' \item{r2}{length-N vector of R-squared values.} +#' \item{resid.sd}{length-N vector of residual standard deviations.} +#' \item{call}{the matched function call.} +#' \item{data}{xts data object containing the assets and factors.} +#' \item{asset.names}{asset.names as input.} +#' \item{fit.method}{fit.method as input.} +#' Where N is the number of assets and T is the +#' number of time periods. +#' +#' @author Yi-An Chen. +#' +#' @references +#' 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. +#' +#' #' Christopherson, J. A., Carino, D. R., & Ferson, W. E. (2009). Portfolio +#' performance measurement and benchmarking. McGraw Hill Professional. pp.127-133 +#' +#' @seealso +#' The original time series function \code{\link{fitTsfm}} and its generic functions +#' application. +#' +#' @examples +#' # load data from the database +#' data(managers) +#' +#' # example: Market-timing factors with LS fit +#' fit <- fitTsfmMT(asset.names=colnames(managers[,(1:6)]), +#' mkt.name="SP500.TR",rf.name="US.3m.TR",data=managers) +#' summary(fit) +#' +#' @importFrom PerformanceAnalytics checkData +#' @importFrom robust lmRob step.lmRob +#' @importFrom leaps regsubsets +#' @importFrom lars lars cv.lars +#' +#' @export + +fitTsfmMT <- function(asset.names,mkt.name, rf.name=NULL, + data=data, fit.method=c("LS","DLS","Robust"), + control=fitTsfm.control(...),...) { + if (is.null(mkt.name)){ + stop("Missing argument: mkt.name has to be specified for market timing model.") + } + + # 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[,mkt.name]) + ### 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)))) + } + + # mkt-timing factors: down.market=max(0,Rf-Rm), market.sqd=(Rm-Rf)^2 + + 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" + factor.names <- c(mkt.name,"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") +# } + + fit.Timing <- fitTsfm(asset.names=asset.names,factor.names=factor.names,rf.name=NULL, + data=dat.xts,fit.method=fit.method,variable.selection="none",control=control) + +return(fit.Timing) +} Modified: pkg/FactorAnalytics/R/fitTsfmUpDn.r =================================================================== --- pkg/FactorAnalytics/R/fitTsfmUpDn.r 2015-03-20 07:33:31 UTC (rev 3621) +++ pkg/FactorAnalytics/R/fitTsfmUpDn.r 2015-03-20 08:48:00 UTC (rev 3622) @@ -1,144 +1,144 @@ -#' @title Fit a up and down market factor model using time series regression -#' -#' @description This is a wrapper function to fits a up and 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. An object of class -#' \code{"tsfmUpDn"} is returned. -#' -#' @details -#' \code{fitTsfmUpDn} will use \code{fitTsfm} to fit a time series model for up and down market respectively. If -#' risk free rate is provided, the up market is the excess market returns which is no less than 0. -#' The goal of up and down market model is to capture two different market Betas in the up and down markets. -#' -#' -#' @param asset.names vector containing names of assets, whose returns or -#' excess returns are the dependent variable. -#' @param mkt.name name of the column for market returns. 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 the market factor (in -#' \code{mkt.name}). Default is \code{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 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 [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3622 From noreply at r-forge.r-project.org Fri Mar 20 20:48:33 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 20 Mar 2015 20:48:33 +0100 (CET) Subject: [Returnanalytics-commits] r3623 - in pkg/FactorAnalytics: R man Message-ID: <20150320194833.C660818765B@r-forge.r-project.org> Author: chenyian Date: 2015-03-20 20:48:33 +0100 (Fri, 20 Mar 2015) New Revision: 3623 Modified: pkg/FactorAnalytics/R/plot.tsfmUpDn.r pkg/FactorAnalytics/man/CornishFisher.Rd pkg/FactorAnalytics/man/fitSfm.Rd pkg/FactorAnalytics/man/fitTsfm.Rd pkg/FactorAnalytics/man/fitTsfm.control.Rd pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd pkg/FactorAnalytics/man/fitTsfmMT.Rd pkg/FactorAnalytics/man/fitTsfmUpDn.Rd pkg/FactorAnalytics/man/fmCov.Rd pkg/FactorAnalytics/man/fmEsDecomp.Rd pkg/FactorAnalytics/man/fmSdDecomp.Rd pkg/FactorAnalytics/man/fmVaRDecomp.Rd pkg/FactorAnalytics/man/paFm.Rd pkg/FactorAnalytics/man/plot.pafm.Rd pkg/FactorAnalytics/man/plot.sfm.Rd pkg/FactorAnalytics/man/plot.tsfm.Rd pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd pkg/FactorAnalytics/man/predict.sfm.Rd pkg/FactorAnalytics/man/predict.tsfm.Rd pkg/FactorAnalytics/man/predict.tsfmUpDn.Rd pkg/FactorAnalytics/man/print.pafm.Rd pkg/FactorAnalytics/man/print.sfm.Rd pkg/FactorAnalytics/man/print.tsfm.Rd pkg/FactorAnalytics/man/print.tsfmUpDn.Rd pkg/FactorAnalytics/man/summary.pafm.Rd pkg/FactorAnalytics/man/summary.sfm.Rd pkg/FactorAnalytics/man/summary.tsfm.Rd pkg/FactorAnalytics/man/summary.tsfmUpDn.Rd Log: debug plot.tsfmUpDn.r 1. change arguments name : SFM.line, LSnRob 2. change legend layout. 3. debug a straight line fitting. Modified: pkg/FactorAnalytics/R/plot.tsfmUpDn.r =================================================================== --- pkg/FactorAnalytics/R/plot.tsfmUpDn.r 2015-03-20 08:48:00 UTC (rev 3622) +++ pkg/FactorAnalytics/R/plot.tsfmUpDn.r 2015-03-20 19:48:33 UTC (rev 3623) @@ -1,148 +1,162 @@ -#' @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 dots are actual values and the dashed lines are fitted values. Users can -#' choose to add a single market factor model and a robust up and down model for comaprsion. -#' -#' For other types of plots, use the list objects \code{Up} and \code{Dn} of class \code{tsfmUpDn}. -#' The \code{plot.tsfm} can be applied. -#' -#' @param x an object of class \code{tsfmUpDn} produced by \code{fitTsfmUpDn}. -#' @param which.assets A vector of character to show single or multiple assets names. The defualt if -#' \code{NULL}. -#' @param line.color A vector of color codes of up/dn fitted line. The first color is for the object fitted -#' line and the second color for the comparison fitted line. The default is \code{c("blue","purple")}. -#' @param line.type The line type of up/dn fitted values. The default is \code{"dotted"}. -#' @param add.legend A logic flag to add a legend. The default is \code{TRUE}. -#' @param add.SFM.line A logic flag to add a fitted single factor model. The default is \code{FALSE}. -#' @param add.comparison A logic flag to add a comparison Up/Down factor model. If the original model -#' is \code{""}, the comparison model is \code{"Robust"} and vice versa. The default is \code{FALSE}. -#' @param show.comparison.legend A logic flag to opt for showing the legend of the comparison model. -#' The default is \code{FALSE}. -#' @param legend.loc The default is \code{"topleft"}. -#' @param legend.cex \code{cex} of \code{legend}. -#' -#' @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 fit -#' fitUpDn <- fitTsfmUpDn(asset.names=colnames(managers[,(1:6)]),mkt.name="SP500.TR", -#' data=managers, fit.method="LS") -#' # plot the fitted model of every assets, press enter to show the next plot. -#' plot(fitUpDn) -#' -#' # or choose to plot one specific asset -#' plot(fitUpDn,which.assets="HAM1") -#' -#' # add a single market factor model fitted line -#' plot(fitUpDn,add.SFM.line=TRUE,which.assets="HAM1") -#' -#' # add Robust Up/Dn model fitted line and change legend to show the robust up/dn Beta -#' plot(fitUpDn,add.comparison=TRUE,show.comparison.legend=TRUE,add.SFM.line=TRUE,which.assets="HAM1") -#' -#' -#' @method plot tsfmUpDn -#' @export - - -plot.tsfmUpDn <- function(x,which.assets=NULL,add.SFM.line=FALSE,add.comparison=FALSE, - line.color=c("blue","purple"),line.type="dotted", - add.legend=TRUE,legend.loc="topleft",legend.cex=0.9, - show.comparison.legend=FALSE,...) { - - # specify the name of market returns and the assets returns - mkt.name = x$Up$factor.names - - # add SFM estimation - - if (add.SFM.line) { - data = x$data - asset.names = x$Up$asset.names - fit.method = x$Up$fit.method - fitSf <- fitTsfm(asset.names=asset.names,factor.names=mkt.name,mkt.name=mkt.name,rf.name=NULL, - data=data,fit.method=fit.method) - plotDataSf <- merge.xts(fitted(fitSf),fitSf$data[,mkt.name]) - } - - # add LS/Robust Up/Dn comparison - - if (add.comparison) { - fit.methods <- c("LS","Robust") - x$call$fit.method <- fit.methods[!fit.methods%in%x$call$fit.method] - x.alt <- eval(x$call) - } - - if (is.null(which.assets)) { - assets.name.all = x$Up$asset.names - } else { - assets.name.all = which.assets - } - while(length(assets.name.all)>0){ - assets.name = assets.name.all[1] - # extract info from the fitTsfm x - plotDataUp <- merge.xts(x$Up$data[,c(assets.name,mkt.name)], fitted(x$Up)[,assets.name]) - colnames(plotDataUp) <- c("ActualUp","MktUp","FittedUp") - plotDataDn <-merge.xts(x$Dn$data[,c(assets.name,mkt.name)], fitted(x$Dn)[,assets.name]) - colnames(plotDataDn) <- c("ActualDn","MktDn","FittedDn") - - plot(rbind(coredata(plotDataUp$MktUp),coredata(plotDataDn$MktDn)), - rbind(coredata(plotDataUp$ActualUp),coredata(plotDataDn$ActualDn)), - xlab=mkt.name,ylab=assets.name,...) - abline(v=0) - lines(coredata(plotDataUp$MktUp),coredata(plotDataUp$FittedUp),col=line.color[1],lty=line.type) - lines(coredata(plotDataDn$MktDn),coredata(plotDataDn$FittedDn),col=line.color[1],lty=line.type) - abline(h=0) - - up.beta <- round(summary(x$Up)$sum.list[[assets.name]]$coefficients[mkt.name,1:2],2) - dn.beta <- round(summary(x$Dn)$sum.list[[assets.name]]$coefficients[mkt.name,1:2],2) - up.beta <- c(as.character(up.beta)[1],paste("(",as.character(up.beta)[2],")",sep="")) - dn.beta <- c(as.character(dn.beta)[1],paste("(",as.character(dn.beta)[2],")",sep="")) - line.col = line.color[1] - # add LS line - if (add.SFM.line){ - lines(coredata(plotDataSf[,assets.name]),coredata(plotDataSf[,mkt.name]),lty="dotted") - legend.name = paste(fit.method,"fitted line",seq="") - - } - - # add alternative Up/Dn model for comparison - if (add.comparison){ - plotDataUp.alt <- merge.xts(x.alt$Up$data[,c(assets.name,mkt.name)], fitted(x.alt$Up)[,assets.name]) - colnames(plotDataUp.alt) <- c("ActualUp","MktUp","FittedUp") - plotDataDn.alt <-merge.xts(x.alt$Dn$data[,c(assets.name,mkt.name)], fitted(x.alt$Dn)[,assets.name]) - colnames(plotDataDn.alt) <- c("ActualDn","MktDn","FittedDn") - lines(coredata(plotDataUp.alt$MktUp),coredata(plotDataUp.alt$FittedUp),col=line.color[2],lty=line.type) - lines(coredata(plotDataDn.alt$MktDn),coredata(plotDataDn.alt$FittedDn),col=line.color[2],lty=line.type) - - # add comparison legend - if (show.comparison.legend) { - up.beta <- round(summary(x.alt$Up)$sum.list[[assets.name]]$coefficients[mkt.name,1:2],2) - dn.beta <- round(summary(x.alt$Dn)$sum.list[[assets.name]]$coefficients[mkt.name,1:2],2) - up.beta <- c(as.character(up.beta)[1],paste("(",as.character(up.beta)[2],")",sep="")) - dn.beta <- c(as.character(dn.beta)[1],paste("(",as.character(dn.beta)[2],")",sep="")) - line.col = line.color[2] - } - } - - if (add.legend){ - legend.txt = c("Up Beta",up.beta,"Dn Beta",dn.beta) - legend.lty = c(line.type,NA,NA,line.type,NA,NA) - legend.col = c(line.col,NA,NA,line.col,NA,NA) - legend(legend.loc,legend=legend.txt,ncol=2,lty=legend.lty,col=legend.col,cex=legend.cex) - - } - assets.name.all <- assets.name.all[-1] - par(ask=TRUE) - } - # turn it back - par(ask=FALSE) +#' @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 dots are actual values and the dashed lines are fitted values. Users can +#' choose to add a single market factor model and a robust up and down model for comaprsion. +#' +#' For other types of plots, use the list objects \code{Up} and \code{Dn} of class \code{tsfmUpDn}. +#' The \code{plot.tsfm} can be applied. +#' +#' @param x an object of class \code{tsfmUpDn} produced by \code{fitTsfmUpDn}. +#' @param asset.name A vector of character to show single or multiple assets names. The defualt if +#' \code{NULL}. +#' @param line.color A vector of color codes of up/dn fitted line. The first color is for the object fitted +#' line and the second color for the comparison fitted line. The default is \code{c("blue","purple")}. +#' @param line.type The line type of up/dn fitted values. The default is \code{"dotted"}. +#' @param add.legend A logic flag to add a legend. The default is \code{TRUE}. +#' @param SFM.line A logic flag to add a fitted single factor model. The default is \code{FALSE}. +#' @param LSnRob A logic flag to add a comparison Up/Down factor model. If the original model +#' is \code{"LS"}, the comparison model is \code{"Robust"} and vice versa. The default is \code{FALSE}. +#' The default is \code{FALSE}. +#' @param legend.loc The default is \code{"topleft"}. +#' @param legend.cex \code{cex} of \code{legend}. +#' +#' @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 fit +#' fitUpDn <- fitTsfmUpDn(asset.names=colnames(managers[,(1:6)]),mkt.name="SP500.TR", +#' data=managers, fit.method="LS") +#' # plot the fitted model of every assets, press enter to show the next plot. +#' plot(fitUpDn) +#' +#' # or choose to plot one specific asset +#' plot(fitUpDn,asset.name="HAM1") +#' +#' # add a single market factor model fitted line +#' plot(fitUpDn,SFM.line=TRUE,asset.name="HAM1") +#' +#' # add Robust Up/Dn model fitted line and change legend to show the robust up/dn Beta +#' plot(fitUpDn,LSnRob=TRUE,asset.name="HAM1") +#' +#' +#' @method plot tsfmUpDn +#' @export + + +plot.tsfmUpDn <- function(x,asset.name=NULL,SFM.line=FALSE,LSnRob=FALSE, + line.color=c("blue","purple"),line.type="dotted", + add.legend=TRUE,legend.loc="topleft",legend.cex=0.9, + ...) { + + # specify the name of market returns and the assets returns + mkt.name = x$Up$factor.names + + # add SFM estimation + + if (SFM.line) { + data = x$data + asset.names = x$Up$asset.names + fit.method = x$Up$fit.method + fitSf <- fitTsfm(asset.names=asset.names,factor.names=mkt.name,mkt.name=mkt.name,rf.name=NULL, + data=data,fit.method=fit.method) + plotDataSf <- merge.xts(fitted(fitSf),fitSf$data[,mkt.name]) + } + + # add LS/Robust Up/Dn comparison + + if (LSnRob) { + fit.methods <- c("LS","Robust") + x$call$fit.method <- fit.methods[!fit.methods%in%x$Up$fit.method] + x.alt <- eval(x$call) + } + + if (is.null(asset.name)) { + assets.name.all = x$Up$asset.names + } else { + assets.name.all = asset.name + } + while(length(assets.name.all)>0){ + assets.name = assets.name.all[1] + # extract info from the fitTsfm x + plotDataUp <- merge.xts(x$Up$data[,c(assets.name,mkt.name)], fitted(x$Up)[,assets.name]) + colnames(plotDataUp) <- c("ActualUp","MktUp","FittedUp") + plotDataDn <-merge.xts(x$Dn$data[,c(assets.name,mkt.name)], fitted(x$Dn)[,assets.name]) + colnames(plotDataDn) <- c("ActualDn","MktDn","FittedDn") + + plot(rbind(coredata(plotDataUp$MktUp),coredata(plotDataDn$MktDn)), + rbind(coredata(plotDataUp$ActualUp),coredata(plotDataDn$ActualDn)), + xlab=mkt.name,ylab=assets.name,...) + abline(v=0) + lines(coredata(plotDataUp$MktUp),coredata(plotDataUp$FittedUp),col=line.color[1],lty=line.type) + lines(coredata(plotDataDn$MktDn),coredata(plotDataDn$FittedDn),col=line.color[1],lty=line.type) + abline(h=0) + + up.beta <- round(summary(x$Up)$sum.list[[assets.name]]$coefficients[mkt.name,1:2],2) + dn.beta <- round(summary(x$Dn)$sum.list[[assets.name]]$coefficients[mkt.name,1:2],2) + up.beta <- paste(as.character(up.beta)[1]," (",as.character(up.beta)[2],")",sep="") + dn.beta <- paste(as.character(dn.beta)[1]," (",as.character(dn.beta)[2],")",sep="") + + # add LS line + if (SFM.line){ + lines(coredata(plotDataSf[,mkt.name]),coredata(plotDataSf[,assets.name]),lty="dotted") + # legend.name = paste(fit.method,"fitted line",seq="") + + } + + # add alternative Up/Dn model for comparison + if (LSnRob){ + plotDataUp.alt <- merge.xts(x.alt$Up$data[,c(assets.name,mkt.name)], fitted(x.alt$Up)[,assets.name]) + colnames(plotDataUp.alt) <- c("ActualUp","MktUp","FittedUp") + plotDataDn.alt <-merge.xts(x.alt$Dn$data[,c(assets.name,mkt.name)], fitted(x.alt$Dn)[,assets.name]) + colnames(plotDataDn.alt) <- c("ActualDn","MktDn","FittedDn") + lines(coredata(plotDataUp.alt$MktUp),coredata(plotDataUp.alt$FittedUp),col=line.color[2],lty=line.type) + lines(coredata(plotDataDn.alt$MktDn),coredata(plotDataDn.alt$FittedDn),col=line.color[2],lty=line.type) + + + up.beta.alt <- round(summary(x.alt$Up)$sum.list[[assets.name]]$coefficients[mkt.name,1:2],2) + dn.beta.alt <- round(summary(x.alt$Dn)$sum.list[[assets.name]]$coefficients[mkt.name,1:2],2) + up.beta.alt <- paste(as.character(up.beta.alt)[1]," (",as.character(up.beta.alt)[2],")",sep="") + dn.beta.alt <- paste(as.character(dn.beta.alt)[1]," (",as.character(dn.beta.alt)[2],")",sep="") + + } + + if (add.legend){ + + if (LSnRob){ + if (x$call$fit.method=="Robust") { + beta.legend = c("Up Beta","Dn Beta","Up BetaRob","Dn BetaRob") + } else { + beta.legend = c("Up BetaRob","Dn BetaRob","Up Beta","Dn Beta") + } + legend.txt = c(beta.legend,up.beta,dn.beta,up.beta.alt,dn.beta.alt) + legend(legend.loc,legend=legend.txt,ncol=2,cex=legend.cex,bty="n") + } else { + if (x$Up$fit.method=="Robust") { + beta.legend = c("Up BetaRob","Dn BetaRob") + } else { + beta.legend = c("Up Beta","Dn Beta") + } + legend.txt = c(beta.legend,up.beta,dn.beta) + legend(legend.loc,legend=legend.txt,ncol=2,cex=legend.cex,bty="n") + } + # legend.lty = c(line.type,NA,NA,line.type,NA,NA) + # legend.col = c(line.col,NA,NA,line.col,NA,NA) + # legend(legend.loc,legend=legend.txt,ncol=2,lty=legend.lty,col=legend.col,cex=legend.cex) + + } + assets.name.all <- assets.name.all[-1] + par(ask=TRUE) + } + # turn it back + par(ask=FALSE) } \ No newline at end of file Modified: pkg/FactorAnalytics/man/CornishFisher.Rd =================================================================== --- pkg/FactorAnalytics/man/CornishFisher.Rd 2015-03-20 08:48:00 UTC (rev 3622) +++ pkg/FactorAnalytics/man/CornishFisher.Rd 2015-03-20 19:48:33 UTC (rev 3623) @@ -1,85 +1,86 @@ -% Generated by roxygen2 (4.0.2): do not edit by hand -\name{dCornishFisher} -\alias{Cornish-Fisher} -\alias{dCornishFisher} -\alias{pCornishFisher} -\alias{qCornishFisher} -\alias{rCornishFisher} -\title{Cornish-Fisher expansion} -\usage{ -dCornishFisher(x, n, skew, ekurt) - -pCornishFisher(q, n, skew, ekurt) - -qCornishFisher(p, n, skew, ekurt) - -rCornishFisher(n, sigma, skew, ekurt, seed = NULL) -} -\arguments{ -\item{x,q}{vector of standardized quantiles.} - -\item{n}{scalar; number of simulated values in random simulation, sample -length in density, distribution and quantile functions.} - -\item{skew}{scalar; skewness.} - -\item{ekurt}{scalar; excess kurtosis.} - -\item{p}{vector of probabilities.} - -\item{sigma}{scalar standard deviation.} - -\item{seed}{scalar; set seed. Default is \code{NULL}.} -} -\value{ -\code{dCornishFisher} gives the density, \code{pCornishFisher} gives the -distribution function, \code{qCornishFisher} gives the quantile function, -and \code{rCornishFisher} generates \code{n} random simulations. -} -\description{ -Density, distribution function, quantile function and random -generation using Cornish-Fisher approximation. -} -\details{ -CDF(q) = Pr(sqrt(n)*(x_bar-mu)/sigma < q) -\code{dCornishFisher} Computes Cornish-Fisher density from two term Edgeworth -expansion given mean, standard deviation, skewness and excess kurtosis. -\code{pCornishFisher} Computes Cornish-Fisher CDF from two term Edgeworth -expansion given mean, standard deviation, skewness and excess kurtosis. -\code{qCornishFisher} Computes Cornish-Fisher quantiles from two term -Edgeworth expansion given mean, standard deviation, skewness and excess -kurtosis. -\code{rCornishFisher} simulates observations based on Cornish-Fisher quantile -expansion given mean, standard deviation, skewness and excess kurtosis. -} -\examples{ -\dontrun{ -# generate 1000 observation from Cornish-Fisher distribution -rc <- rCornishFisher(1000,1,0,5) -hist(rc, breaks=100, freq=FALSE, - main="simulation of Cornish Fisher Distribution", xlim=c(-10,10)) -lines(seq(-10,10,0.1), dnorm(seq(-10,10,0.1), mean=0, sd=1), col=2) -# compare with standard normal curve - -# exponential example from A.dasGupta p.188 -# x is iid exp(1) distribution, sample size = 5 -# then x_bar is Gamma(shape=5, scale=1/5) distribution -q <- c(0,0.4,1,2) -# exact cdf -pgamma(q/sqrt(5)+1, shape=5, scale=1/5) -# use CLT -pnorm(q) -# use edgeworth expansion -pCornishFisher(q, n=5, skew=2, ekurt=6) -} -} -\author{ -Eric Zivot and Yi-An Chen. -} -\references{ -DasGupta, A. (2008). Asymptotic theory of statistics and probability. -Springer. -Severini, T. A., (2000). Likelihood Methods in Statistics. Oxford University -Press. -} - +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/CornishFisher.R +\name{dCornishFisher} +\alias{Cornish-Fisher} +\alias{dCornishFisher} +\alias{pCornishFisher} +\alias{qCornishFisher} +\alias{rCornishFisher} +\title{Cornish-Fisher expansion} +\usage{ +dCornishFisher(x, n, skew, ekurt) + +pCornishFisher(q, n, skew, ekurt) + +qCornishFisher(p, n, skew, ekurt) + +rCornishFisher(n, sigma, skew, ekurt, seed = NULL) +} +\arguments{ +\item{x,q}{vector of standardized quantiles.} + +\item{n}{scalar; number of simulated values in random simulation, sample +length in density, distribution and quantile functions.} + +\item{skew}{scalar; skewness.} + +\item{ekurt}{scalar; excess kurtosis.} + +\item{p}{vector of probabilities.} + +\item{sigma}{scalar standard deviation.} + +\item{seed}{scalar; set seed. Default is \code{NULL}.} +} +\value{ +\code{dCornishFisher} gives the density, \code{pCornishFisher} gives the +distribution function, \code{qCornishFisher} gives the quantile function, +and \code{rCornishFisher} generates \code{n} random simulations. +} +\description{ +Density, distribution function, quantile function and random +generation using Cornish-Fisher approximation. +} +\details{ +CDF(q) = Pr(sqrt(n)*(x_bar-mu)/sigma < q) +\code{dCornishFisher} Computes Cornish-Fisher density from two term Edgeworth +expansion given mean, standard deviation, skewness and excess kurtosis. +\code{pCornishFisher} Computes Cornish-Fisher CDF from two term Edgeworth +expansion given mean, standard deviation, skewness and excess kurtosis. +\code{qCornishFisher} Computes Cornish-Fisher quantiles from two term +Edgeworth expansion given mean, standard deviation, skewness and excess +kurtosis. +\code{rCornishFisher} simulates observations based on Cornish-Fisher quantile +expansion given mean, standard deviation, skewness and excess kurtosis. +} +\examples{ +\dontrun{ +# generate 1000 observation from Cornish-Fisher distribution +rc <- rCornishFisher(1000,1,0,5) +hist(rc, breaks=100, freq=FALSE, + main="simulation of Cornish Fisher Distribution", xlim=c(-10,10)) +lines(seq(-10,10,0.1), dnorm(seq(-10,10,0.1), mean=0, sd=1), col=2) +# compare with standard normal curve + +# exponential example from A.dasGupta p.188 +# x is iid exp(1) distribution, sample size = 5 +# then x_bar is Gamma(shape=5, scale=1/5) distribution +q <- c(0,0.4,1,2) +# exact cdf +pgamma(q/sqrt(5)+1, shape=5, scale=1/5) +# use CLT +pnorm(q) +# use edgeworth expansion +pCornishFisher(q, n=5, skew=2, ekurt=6) +} +} +\author{ +Eric Zivot and Yi-An Chen. +} +\references{ +DasGupta, A. (2008). Asymptotic theory of statistics and probability. +Springer. +Severini, T. A., (2000). Likelihood Methods in Statistics. Oxford University +Press. +} + Modified: pkg/FactorAnalytics/man/fitSfm.Rd =================================================================== --- pkg/FactorAnalytics/man/fitSfm.Rd 2015-03-20 08:48:00 UTC (rev 3622) +++ pkg/FactorAnalytics/man/fitSfm.Rd 2015-03-20 19:48:33 UTC (rev 3623) @@ -1,179 +1,180 @@ -% Generated by roxygen2 (4.0.2): do not edit by hand -\name{fitSfm} -\alias{coef.sfm} -\alias{fitSfm} -\alias{fitted.sfm} -\alias{residuals.sfm} -\title{Fit a statistical factor model using principal component analysis} -\usage{ -fitSfm(data, k = 1, max.k = NULL, refine = TRUE, sig = 0.05, - check = FALSE, corr = FALSE, ...) - -\method{coef}{sfm}(object, ...) - -\method{fitted}{sfm}(object, ...) - -\method{residuals}{sfm}(object, ...) -} -\arguments{ -\item{data}{vector, matrix, data.frame, xts, timeSeries or zoo object with -asset returns. See details.} - -\item{k}{number of factors; a number (or) a method for determining the -optimal number of factors, one of "bn" or "ck". See details. Default is 1.} - -\item{max.k}{scalar; the maximum number of factors to be considered for -methods "bn" or "ck". Default is \code{NULL}. See details.} - -\item{refine}{logical; whether to use the Connor-Korajczyk refinement for -APCA. Default is \code{TRUE}.} - -\item{sig}{scalar; desired level of significance when "ck" method is -specified. Default is 0.05.} - -\item{check}{logical; to check if any asset has identical observations. -Default is \code{FALSE}.} - -\item{corr}{logical; whether to use the correlation instead of the covariance -matrix when finding the principal components. Default is \code{FALSE}.} - -\item{...}{optional arguments passed to \code{\link[stats]{lm}}.} - -\item{object}{a fit object of class \code{sfm} which is returned by -\code{fitSfm}} -} -\value{ -fitTsfm returns an object of class \code{"sfm"} 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{"sfm"} is a list containing the following -components: -\item{asset.fit}{fitted object of class \code{"mlm"} or \code{"lm"} from the -time-series LS regression of asset returns on estimated factors.} -\item{k}{number of factors; as input or determined by "ck" or "bn" methods.} -\item{factors}{T x K xts object of estimated factor realizations.} -\item{loadings}{N x K matrix of factor loadings estimated by -regressing the asset returns on estimated factors.} -\item{alpha}{length-N vector of estimated alphas.} -\item{r2}{length-N vector of R-squared values.} -\item{resid.sd}{length-N vector of residual standard deviations.} -\item{residuals}{T x N xts object of residuals from the LS regression.} -\item{Omega}{N x N return covariance matrix estimated by the factor model.} -\item{eigen}{length-N (or length-T for APCA) vector of eigenvalues of the -sample covariance matrix.} -\item{mimic}{N x K matrix of factor mimicking portfolio weights.} -\item{call}{the matched function call.} -\item{data}{T x N xts data object containing the asset returns.} -\item{asset.names}{length-N vector of column names from data.} -Where N is the number of assets, K is the number of factors, and T is the -number of observations. -} -\description{ -Fits a statistical factor model using Principal Component -Analysis (PCA) for one or more asset returns or excess returns. When the -number of assets exceeds the number of time periods, Asymptotic Principal -Component Analysis (APCA) is performed. An object of class \code{"sfm"} is -returned. This function is based on the S+FinMetric function \code{mfactor}. -} -\details{ -If \code{data} is not of class \code{"xts"}, rownames must provide an -\code{"xts"} compatible time index. Before model fitting, incomplete cases in -\code{data} are removed using \code{\link[stats]{na.omit}}. Specifying -\code{check=TRUE}, issues a warning if any asset is found to have identical -observations. - -Let \code{N} be the number of columns or assets and \code{T} be the number -of rows or observations. When \code{N < T}, Principal Component Analysis -(PCA) is performed. Otherwise, Asymptotic Principal Component Analysis -(APCA) is performed. In either case, any number of factors less than -\code{min(N,T)} can be chosen via argument \code{k}. Default is 1. Refer to -Zivot and Wang (2007) for more details and references. - -Alternately, for APCA, a method to determine the number of factors can be -specified: \code{k="bn"} corresponds to Bai and Ng (2002) and \code{k="ck"} -corresponds to Connor and Korajczyk (1993). User can specify the maximum -number of factors, \code{max.k} to consider with these methods. If not, it -is assumed to be either 10 or $T-1$, whichever is smaller. - -\code{refine} specifies whether a refinement of the APCA procedure from -Connor and Korajczyk (1988) that may improve efficiency is to be used. - -When \code{corr=TRUE}, the correlation matrix of returns are used for -finding the principal components instead of the covariance matrix. This is -typically decided by practioners on a case-by-case basis. The variable with -the highest variance dominates the PCA when the covariance matrix is used. -However, this may be justified if a volatile asset is more interesting for -some reason and volatility information shouldn't be discarded. On the other -hand, using the correlation matrix standardizes the variables and makes them -comparable, avoiding penalizing variables with less dispersion. - -Finally, if the median of the 1st principal component is negative, all it's -factor realizations are automatically inverted to enable more meaningful -interpretation. -} -\examples{ -# load return data -data(StockReturns) - -# PCA is performed on r.M and APCA on r.W -class(r.M) -dim(r.M) -range(rownames(r.M)) -class(r.W) -dim(r.W) - -# PCA -args(fitSfm) -fit.pca <- fitSfm(r.M, k=2) -class(fit.pca) -names(fit.pca) -head(fit.pca$factors) -head(fit.pca$loadings) -fit.pca$r2 -fit.pca$resid.sd -fit.pca$mimic - -# APCA with number of factors, k=15 -fit.apca <- fitSfm(r.W, k=15, refine=TRUE) - -# APCA with the Bai & Ng method -fit.apca.bn <- fitSfm(r.W, k="bn") - -# APCA with the Connor-Korajczyk method -fit.apca.ck <- fitSfm(r.W, k="ck") -} -\author{ -Eric Zivot, Sangeetha Srinivasan and Yi-An Chen -} -\references{ -Bai, J., & Ng, S. (2002). Determining the number of factors in approximate -factor models. Econometrica, 70(1), 191-221. - -Connor, G., & Korajczyk, R. A. (1988). Risk and return in an equilibrium -APT: Application of a new test methodology. Journal of Financial Economics, -21(2), 255-289. - -Connor, G., & Korajczyk, R. A. (1993). A test for the number of factors in -an approximate factor model. The Journal of Finance, 48(4), 1263-1291. - -Zivot, E., & Wang, J. (2007). Modeling Financial Time Series with S-PLUS -(Vol. 191). Springer. -} -\seealso{ -The \code{sfm} methods for generic functions: -\code{\link{plot.sfm}}, \code{\link{predict.sfm}}, -\code{\link{print.sfm}} and \code{\link{summary.sfm}}. - -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. -} - +% Generated by roxygen2 (4.1.0): do not edit by hand +% Please edit documentation in R/fitSfm.R +\name{fitSfm} +\alias{coef.sfm} +\alias{fitSfm} +\alias{fitted.sfm} +\alias{residuals.sfm} +\title{Fit a statistical factor model using principal component analysis} +\usage{ +fitSfm(data, k = 1, max.k = NULL, refine = TRUE, sig = 0.05, + check = FALSE, corr = FALSE, ...) + +\method{coef}{sfm}(object, ...) + +\method{fitted}{sfm}(object, ...) + +\method{residuals}{sfm}(object, ...) +} +\arguments{ +\item{data}{vector, matrix, data.frame, xts, timeSeries or zoo object with +asset returns. See details.} + +\item{k}{number of factors; a number (or) a method for determining the +optimal number of factors, one of "bn" or "ck". See details. Default is 1.} + +\item{max.k}{scalar; the maximum number of factors to be considered for +methods "bn" or "ck". Default is \code{NULL}. See details.} + +\item{refine}{logical; whether to use the Connor-Korajczyk refinement for +APCA. Default is \code{TRUE}.} + +\item{sig}{scalar; desired level of significance when "ck" method is +specified. Default is 0.05.} + +\item{check}{logical; to check if any asset has identical observations. +Default is \code{FALSE}.} + +\item{corr}{logical; whether to use the correlation instead of the covariance +matrix when finding the principal components. Default is \code{FALSE}.} + +\item{...}{optional arguments passed to \code{\link[stats]{lm}}.} + +\item{object}{a fit object of class \code{sfm} which is returned by +\code{fitSfm}} +} +\value{ +fitTsfm returns an object of class \code{"sfm"} 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{"sfm"} is a list containing the following +components: +\item{asset.fit}{fitted object of class \code{"mlm"} or \code{"lm"} from the +time-series LS regression of asset returns on estimated factors.} +\item{k}{number of factors; as input or determined by "ck" or "bn" methods.} +\item{factors}{T x K xts object of estimated factor realizations.} +\item{loadings}{N x K matrix of factor loadings estimated by +regressing the asset returns on estimated factors.} +\item{alpha}{length-N vector of estimated alphas.} +\item{r2}{length-N vector of R-squared values.} +\item{resid.sd}{length-N vector of residual standard deviations.} +\item{residuals}{T x N xts object of residuals from the LS regression.} +\item{Omega}{N x N return covariance matrix estimated by the factor model.} +\item{eigen}{length-N (or length-T for APCA) vector of eigenvalues of the +sample covariance matrix.} +\item{mimic}{N x K matrix of factor mimicking portfolio weights.} +\item{call}{the matched function call.} +\item{data}{T x N xts data object containing the asset returns.} +\item{asset.names}{length-N vector of column names from data.} +Where N is the number of assets, K is the number of factors, and T is the +number of observations. +} +\description{ +Fits a statistical factor model using Principal Component +Analysis (PCA) for one or more asset returns or excess returns. When the +number of assets exceeds the number of time periods, Asymptotic Principal +Component Analysis (APCA) is performed. An object of class \code{"sfm"} is +returned. This function is based on the S+FinMetric function \code{mfactor}. +} +\details{ +If \code{data} is not of class \code{"xts"}, rownames must provide an +\code{"xts"} compatible time index. Before model fitting, incomplete cases in +\code{data} are removed using \code{\link[stats]{na.omit}}. Specifying +\code{check=TRUE}, issues a warning if any asset is found to have identical +observations. + +Let \code{N} be the number of columns or assets and \code{T} be the number +of rows or observations. When \code{N < T}, Principal Component Analysis +(PCA) is performed. Otherwise, Asymptotic Principal Component Analysis +(APCA) is performed. In either case, any number of factors less than +\code{min(N,T)} can be chosen via argument \code{k}. Default is 1. Refer to +Zivot and Wang (2007) for more details and references. + +Alternately, for APCA, a method to determine the number of factors can be +specified: \code{k="bn"} corresponds to Bai and Ng (2002) and \code{k="ck"} +corresponds to Connor and Korajczyk (1993). User can specify the maximum +number of factors, \code{max.k} to consider with these methods. If not, it +is assumed to be either 10 or $T-1$, whichever is smaller. + +\code{refine} specifies whether a refinement of the APCA procedure from +Connor and Korajczyk (1988) that may improve efficiency is to be used. + +When \code{corr=TRUE}, the correlation matrix of returns are used for +finding the principal components instead of the covariance matrix. This is +typically decided by practioners on a case-by-case basis. The variable with [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3623 From noreply at r-forge.r-project.org Fri Mar 20 23:45:36 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 20 Mar 2015 23:45:36 +0100 (CET) Subject: [Returnanalytics-commits] r3624 - in pkg/FactorAnalytics: R man Message-ID: <20150320224536.4C22A1875A0@r-forge.r-project.org> Author: chenyian Date: 2015-03-20 23:45:36 +0100 (Fri, 20 Mar 2015) New Revision: 3624 Modified: pkg/FactorAnalytics/R/plot.tsfmUpDn.r pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd Log: fine tuning of plot.tsfmUpDn.r for line types, colors, width and the legend. Modified: pkg/FactorAnalytics/R/plot.tsfmUpDn.r =================================================================== --- pkg/FactorAnalytics/R/plot.tsfmUpDn.r 2015-03-20 19:48:33 UTC (rev 3623) +++ pkg/FactorAnalytics/R/plot.tsfmUpDn.r 2015-03-20 22:45:36 UTC (rev 3624) @@ -13,18 +13,21 @@ #' @param x an object of class \code{tsfmUpDn} produced by \code{fitTsfmUpDn}. #' @param asset.name A vector of character to show single or multiple assets names. The defualt if #' \code{NULL}. -#' @param line.color A vector of color codes of up/dn fitted line. The first color is for the object fitted -#' line and the second color for the comparison fitted line. The default is \code{c("blue","purple")}. -#' @param line.type The line type of up/dn fitted values. The default is \code{"dotted"}. +#' @param line.color A vector of color codes of up/dn fitted line. The first element is for the object fitted +#' line and the second for the comparison fitted line. The default is \code{c("blue","purple")}. +#' @param line.type A vector of line types of up/dn fitted line. The first is for the object fitted +#' line and the second for the comparison fitted line. The default is \code{c("dashed","solid"}. +#' @param line.width A vector of line width of up/dn fitted line. The first element is for the object fitted +#' line and the second element for the comparison fitted line. The default is \code{c(1,2}. #' @param add.legend A logic flag to add a legend. The default is \code{TRUE}. #' @param SFM.line A logic flag to add a fitted single factor model. The default is \code{FALSE}. -#' @param LSnRob A logic flag to add a comparison Up/Down factor model. If the original model +#' @param sfm.line.type SFM line type. The default is \code{"dashed"} +#' @param LSandRob A logic flag to add a comparison Up/Down factor model. If the original model #' is \code{"LS"}, the comparison model is \code{"Robust"} and vice versa. The default is \code{FALSE}. #' The default is \code{FALSE}. #' @param legend.loc The default is \code{"topleft"}. #' @param legend.cex \code{cex} of \code{legend}. -#' -#' @param ... Other arguments can be used in \code{plot}. +#' @param ... Other arguments can be used in \code{plot}. Please refer to \code{plot}. #' @author Yi-An Chen #' #' @seealso \code{\link{fitTsfmUpDn}} @@ -46,17 +49,17 @@ #' plot(fitUpDn,SFM.line=TRUE,asset.name="HAM1") #' #' # add Robust Up/Dn model fitted line and change legend to show the robust up/dn Beta -#' plot(fitUpDn,LSnRob=TRUE,asset.name="HAM1") +#' plot(fitUpDn,LSandRob=TRUE,asset.name="HAM1") #' #' #' @method plot tsfmUpDn #' @export -plot.tsfmUpDn <- function(x,asset.name=NULL,SFM.line=FALSE,LSnRob=FALSE, - line.color=c("blue","purple"),line.type="dotted", - add.legend=TRUE,legend.loc="topleft",legend.cex=0.9, - ...) { +plot.tsfmUpDn <- function(x,asset.name=NULL,SFM.line=FALSE,LSandRob=FALSE, + line.color=c("blue","purple"),line.type=c("dashed","solid"), + line.width=c(1,2),sfm.line.type = "dashed", + add.legend=TRUE,legend.loc="topleft",legend.cex=0.9,...) { # specify the name of market returns and the assets returns mkt.name = x$Up$factor.names @@ -74,7 +77,7 @@ # add LS/Robust Up/Dn comparison - if (LSnRob) { + if (LSandRob) { fit.methods <- c("LS","Robust") x$call$fit.method <- fit.methods[!fit.methods%in%x$Up$fit.method] x.alt <- eval(x$call) @@ -97,8 +100,8 @@ rbind(coredata(plotDataUp$ActualUp),coredata(plotDataDn$ActualDn)), xlab=mkt.name,ylab=assets.name,...) abline(v=0) - lines(coredata(plotDataUp$MktUp),coredata(plotDataUp$FittedUp),col=line.color[1],lty=line.type) - lines(coredata(plotDataDn$MktDn),coredata(plotDataDn$FittedDn),col=line.color[1],lty=line.type) + lines(coredata(plotDataUp$MktUp),coredata(plotDataUp$FittedUp),col=line.color[1],lty=line.type[1],lwd=line.width[1]) + lines(coredata(plotDataDn$MktDn),coredata(plotDataDn$FittedDn),col=line.color[1],lty=line.type[1],lwd=line.width[1]) abline(h=0) up.beta <- round(summary(x$Up)$sum.list[[assets.name]]$coefficients[mkt.name,1:2],2) @@ -108,19 +111,19 @@ # add LS line if (SFM.line){ - lines(coredata(plotDataSf[,mkt.name]),coredata(plotDataSf[,assets.name]),lty="dotted") + lines(coredata(plotDataSf[,mkt.name]),coredata(plotDataSf[,assets.name]),lty=sfm.line.type) # legend.name = paste(fit.method,"fitted line",seq="") } # add alternative Up/Dn model for comparison - if (LSnRob){ + if (LSandRob){ plotDataUp.alt <- merge.xts(x.alt$Up$data[,c(assets.name,mkt.name)], fitted(x.alt$Up)[,assets.name]) colnames(plotDataUp.alt) <- c("ActualUp","MktUp","FittedUp") plotDataDn.alt <-merge.xts(x.alt$Dn$data[,c(assets.name,mkt.name)], fitted(x.alt$Dn)[,assets.name]) colnames(plotDataDn.alt) <- c("ActualDn","MktDn","FittedDn") - lines(coredata(plotDataUp.alt$MktUp),coredata(plotDataUp.alt$FittedUp),col=line.color[2],lty=line.type) - lines(coredata(plotDataDn.alt$MktDn),coredata(plotDataDn.alt$FittedDn),col=line.color[2],lty=line.type) + lines(coredata(plotDataUp.alt$MktUp),coredata(plotDataUp.alt$FittedUp),col=line.color[2],lty=line.type[2],lwd=line.width[2]) + lines(coredata(plotDataDn.alt$MktDn),coredata(plotDataDn.alt$FittedDn),col=line.color[2],lty=line.type[2],lwd=line.width[2]) up.beta.alt <- round(summary(x.alt$Up)$sum.list[[assets.name]]$coefficients[mkt.name,1:2],2) @@ -132,22 +135,32 @@ if (add.legend){ - if (LSnRob){ + if (LSandRob){ if (x$call$fit.method=="Robust") { - beta.legend = c("Up Beta","Dn Beta","Up BetaRob","Dn BetaRob") + beta.legend = c(paste("Up Beta"," =",up.beta,seq=""), + paste("Up BetaRob =",up.beta.alt,seq=""), + paste("Dn Beta"," =",dn.beta,seq=""), + paste("Dn BetaRob =",dn.beta.alt,seq="")) } else { - beta.legend = c("Up BetaRob","Dn BetaRob","Up Beta","Dn Beta") + beta.legend = c("Up BetaRob","Up Beta","Dn BetaRob","Dn Beta") + beta.legend = c(paste("Up BetaRob =",up.beta.alt,seq=""), + paste("Up Beta"," =",up.beta,seq=""), + paste("Dn BetaRob =",dn.beta.alt,seq=""), + paste("Dn Beta"," =",dn.beta,seq="")) + } - legend.txt = c(beta.legend,up.beta,dn.beta,up.beta.alt,dn.beta.alt) - legend(legend.loc,legend=legend.txt,ncol=2,cex=legend.cex,bty="n") + legend(legend.loc,legend=beta.legend,ncol=1,cex=legend.cex,bty="n",lty=rep(line.type,2),col=rep(line.color,2)) } else { if (x$Up$fit.method=="Robust") { - beta.legend = c("Up BetaRob","Dn BetaRob") + beta.legend = c(paste("Up BetaRob =",up.beta.alt,seq=""), + paste("Dn BetaRob =",dn.beta.alt,seq="")) } else { beta.legend = c("Up Beta","Dn Beta") + beta.legend = c(paste("Up Beta =",up.beta,seq=""), + paste("Dn Beta =",dn.beta,seq="")) } - legend.txt = c(beta.legend,up.beta,dn.beta) - legend(legend.loc,legend=legend.txt,ncol=2,cex=legend.cex,bty="n") + + legend(legend.loc,legend=beta.legend,ncol=1,cex=legend.cex,bty="n") } # legend.lty = c(line.type,NA,NA,line.type,NA,NA) # legend.col = c(line.col,NA,NA,line.col,NA,NA) Modified: pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd =================================================================== --- pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd 2015-03-20 19:48:33 UTC (rev 3623) +++ pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd 2015-03-20 22:45:36 UTC (rev 3624) @@ -5,8 +5,10 @@ \title{Plot actual against fitted values of up and down market time series factor model} \usage{ \method{plot}{tsfmUpDn}(x, asset.name = NULL, SFM.line = FALSE, - LSnRob = FALSE, line.color = c("blue", "purple"), line.type = "dotted", - add.legend = TRUE, legend.loc = "topleft", legend.cex = 0.9, ...) + LSandRob = FALSE, line.color = c("blue", "purple"), + line.type = c("dashed", "solid"), line.width = c(1, 2), + sfm.line.type = "dashed", add.legend = TRUE, legend.loc = "topleft", + legend.cex = 0.9, ...) } \arguments{ \item{x}{an object of class \code{tsfmUpDn} produced by \code{fitTsfmUpDn}.} @@ -16,22 +18,28 @@ \item{SFM.line}{A logic flag to add a fitted single factor model. The default is \code{FALSE}.} -\item{LSnRob}{A logic flag to add a comparison Up/Down factor model. If the original model +\item{LSandRob}{A logic flag to add a comparison Up/Down factor model. If the original model is \code{"LS"}, the comparison model is \code{"Robust"} and vice versa. The default is \code{FALSE}. The default is \code{FALSE}.} -\item{line.color}{A vector of color codes of up/dn fitted line. The first color is for the object fitted -line and the second color for the comparison fitted line. The default is \code{c("blue","purple")}.} +\item{line.color}{A vector of color codes of up/dn fitted line. The first element is for the object fitted +line and the second for the comparison fitted line. The default is \code{c("blue","purple")}.} -\item{line.type}{The line type of up/dn fitted values. The default is \code{"dotted"}.} +\item{line.type}{A vector of line types of up/dn fitted line. The first is for the object fitted +line and the second for the comparison fitted line. The default is \code{c("dashed","solid"}.} +\item{line.width}{A vector of line width of up/dn fitted line. The first element is for the object fitted +line and the second element for the comparison fitted line. The default is \code{c(1,2}.} + +\item{sfm.line.type}{SFM line type. The default is \code{"dashed"}} + \item{add.legend}{A logic flag to add a legend. The default is \code{TRUE}.} \item{legend.loc}{The default is \code{"topleft"}.} \item{legend.cex}{\code{cex} of \code{legend}.} -\item{...}{Other arguments can be used in \code{plot}.} +\item{...}{Other arguments can be used in \code{plot}. Please refer to \code{plot}.} } \description{ Generic \code{plot} method for object of class \code{tsfmUpDn}. @@ -60,7 +68,7 @@ plot(fitUpDn,SFM.line=TRUE,asset.name="HAM1") # add Robust Up/Dn model fitted line and change legend to show the robust up/dn Beta - plot(fitUpDn,LSnRob=TRUE,asset.name="HAM1") + plot(fitUpDn,LSandRob=TRUE,asset.name="HAM1") } \author{ Yi-An Chen From noreply at r-forge.r-project.org Sun Mar 22 08:08:56 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 22 Mar 2015 08:08:56 +0100 (CET) Subject: [Returnanalytics-commits] r3625 - in pkg/PortfolioAnalytics: . vignettes Message-ID: <20150322070856.27417183FEF@r-forge.r-project.org> Author: rossbennett34 Date: 2015-03-22 08:08:55 +0100 (Sun, 22 Mar 2015) New Revision: 3625 Added: pkg/PortfolioAnalytics/vignettes/portfolio_vignette.Rnw Modified: pkg/PortfolioAnalytics/DESCRIPTION Log: fixed bug in vignette that was preventing compile to pdf Modified: pkg/PortfolioAnalytics/DESCRIPTION =================================================================== --- pkg/PortfolioAnalytics/DESCRIPTION 2015-03-20 22:45:36 UTC (rev 3624) +++ pkg/PortfolioAnalytics/DESCRIPTION 2015-03-22 07:08:55 UTC (rev 3625) @@ -11,7 +11,7 @@ , person(given="Guy",family="Yollin",role="ctb") , person(given="R. Douglas",family="Martin",role="ctb") ) -Version: 0.9.3606 +Version: 0.9.3625 Date: $Date$ Maintainer: Brian G. Peterson Description: Portfolio optimization and analysis routines and graphics. Added: pkg/PortfolioAnalytics/vignettes/portfolio_vignette.Rnw =================================================================== --- pkg/PortfolioAnalytics/vignettes/portfolio_vignette.Rnw (rev 0) +++ pkg/PortfolioAnalytics/vignettes/portfolio_vignette.Rnw 2015-03-22 07:08:55 UTC (rev 3625) @@ -0,0 +1,680 @@ +\documentclass[a4paper]{article} +\usepackage[OT1]{fontenc} +\usepackage{Rd} +\usepackage{amsmath} +\usepackage{hyperref} + +\usepackage[round]{natbib} +\usepackage{bm} +\usepackage{verbatim} +\usepackage[latin1]{inputenc} +\bibliographystyle{abbrvnat} + +\usepackage{url} + +\let\proglang=\textsf +%\newcommand{\pkg}[1]{{\fontseries{b}\selectfont #1}} +%\newcommand{\R}[1]{{\fontseries{b}\selectfont #1}} +%\newcommand{\email}[1]{\href{mailto:#1}{\normalfont\texttt{#1}}} +%\newcommand{\E}{\mathsf{E}} +%\newcommand{\VAR}{\mathsf{VAR}} +%\newcommand{\COV}{\mathsf{COV}} +%\newcommand{\Prob}{\mathsf{P}} + +\renewcommand{\topfraction}{0.85} +\renewcommand{\textfraction}{0.1} +\renewcommand{\baselinestretch}{1.5} +\setlength{\textwidth}{15cm} \setlength{\textheight}{22cm} \topmargin-1cm \evensidemargin0.5cm \oddsidemargin0.5cm + +\usepackage[latin1]{inputenc} +% or whatever + +\usepackage{lmodern} +\usepackage[T1]{fontenc} +% Or whatever. Note that the encoding and the font should match. If T1 +% does not look nice, try deleting the line with the fontenc. + +% \VignetteIndexEntry{An Introduction to Portfolio Optimization with PortfolioAnalytics} + +\begin{document} + +\title{Introduction to PortfolioAnalytics} +\author{Ross Bennett} + +\maketitle + +\begin{abstract} +The purpose of this vignette is to demonstrate the new interface in PortfolioAnalytics to specify a portfolio object, add constraints and objectis, and run optimizations. +\end{abstract} + +\tableofcontents + +\section{Getting Started} +\subsection{Load Packages} +Load the necessary packages. + +<<>>= +library(PortfolioAnalytics) +@ + +\subsection{Data} +The edhec data set from the PerformanceAnalytics package will be used as example data. +<<>>= +data(edhec) + +# Use the first 4 columns in edhec for a returns object +returns <- edhec[, 1:4] +colnames(returns) <- c("CA", "CTAG", "DS", "EM") +print(head(returns, 5)) + +# Get a character vector of the fund names +fund.names <- colnames(returns) +@ + +\section{Creating the Portfolio Object} +The portfolio object is instantiated with the \code{portfolio.spec} function. The main argument to \code{portfolio.spec} is assets, this is a required argument. The assets argument can be a scalar value for the number of assets, a character vector of fund names, or a named vector of initial weights. If initial weights are not specified, an equal weight portfolio will be assumed. + +The \code{pspec} object is an S3 object of class "portfolio". When first created, the portfolio object has an element named \code{assets} with the initial weights, an element named \code{category\_labels}, an element named \code{weight\_seq} with sequence of weights if specified, an empty constraints list and an empty objectives list. + +<<>>= +# Specify a portfolio object by passing a character vector for the +# assets argument. +pspec <- portfolio.spec(assets=fund.names) +print.default(pspec) +@ + +\section{Adding Constraints to the Portfolio Object} +Adding constraints to the portfolio object is done with \code{add.constraint}. The \code{add.constraint} function is the main interface for adding and/or updating constraints to the portfolio object. This function allows the user to specify the portfolio to add the constraints to, the type of constraints, arguments for the constraint, and whether or not to enable the constraint (\code{enabled=TRUE} is the default). If updating an existing constraint, the indexnum argument can be specified. + +\subsection{Sum of Weights Constraint} + +The \code{weight\_sum} constraint specifies the constraint on the sum of the weights. Aliases for the \code{weight\_sum} constraint type include \code{weight} and \code{leverage}. Here we add a constraint that the weights must sum to 1, or the full investment constraint. +<>= +# Add the full investment constraint that specifies the weights must sum to 1. +pspec <- add.constraint(portfolio=pspec, + type="weight_sum", + min_sum=1, + max_sum=1) +@ + +There are two special cases for the leverage constraint: +\begin{enumerate} +\item The sum of the weights equal 1, i.e. the full investment constraint. The full investment constraint can be specified with \code{type="full\_investment"}. This automatically sets \code{min\_sum=1} and \code{max\_sum=1.} +\item The sum of the weights equal 0, i.e. the dollar neutral or active constraint. This constraint can be specified with \code{type="dollar\_neutral"} or \code{type="active"}. +\end{enumerate} + +<>= +# The full investment constraint can also be specified with type="full_investment" +# pspec <- add.constraint(portfolio=pspec, type="full_investment") + +# Another common constraint is that portfolio weights sum to 0. +# This can be specified any of the following ways +# pspec <- add.constraint(portfolio=pspec, type="weight_sum", +# min_sum=0, +# max_sum=0) +# pspec <- add.constraint(portfolio=pspec, type="dollar_neutral") +# pspec <- add.constraint(portfolio=pspec, type="active") +@ + +\subsection{Box Constraint} +Box constraints allows the user to specify upper and lower bounds on the weights of the assets. Here we add box constraints for the asset weights so that the minimum weight of any asset must be greater than or equal to 0.05 and the maximum weight of any asset must be less than or equal to 0.4. The values for min and max can be passed in as scalars or vectors. If min and max are scalars, the values for min and max will be replicated as vectors to the length of assets. If min and max are not specified, a minimum weight of 0 and maximum weight of 1 are assumed. Note that min and max can be specified as vectors with different weights for linear inequality constraints. +<>= +# Add box constraints +pspec <- add.constraint(portfolio=pspec, + type="box", + min=0.05, + max=0.4) + +# min and max can also be specified per asset +# pspec <- add.constraint(portfolio=pspec, +# type="box", +# min=c(0.05, 0, 0.08, 0.1), +# max=c(0.4, 0.3, 0.7, 0.55)) + +# A special case of box constraints is long only where min=0 and max=1 +# The default action is long only if min and max are not specified +# pspec <- add.constraint(portfolio=pspec, type="box") +# pspec <- add.constraint(portfolio=pspec, type="long_only") +@ + + +\subsection{Group Constraint} +Group constraints allow the user to specify the the sum of weights by group. Group constraints are currently supported by the ROI, DEoptim, and random portfolio solvers. The following code groups the assets such that the first 3 assets are grouped together labeled GroupA and the fourth asset is in its own group labeled GroupB. The \code{group\_min} argument specifies that the sum of the weights in GroupA must be greater than or equal to 0.1 and the sum of the weights in GroupB must be greater than or equal to 0.15. The \code{group\_max} argument specifies that the sum of the weights in GroupA must be less than or equal to 0.85 and the sum of the weights in GroupB must be less than or equal to 0.55.The \code{group\_labels} argument is optional and is useful if groups is not a named list for labeling groups in terms of market capitalization, sector, etc. +<>= +# Add group constraints +pspec <- add.constraint(portfolio=pspec, type="group", + groups=list(groupA=c(1, 2, 3), + grouB=4), + group_min=c(0.1, 0.15), + group_max=c(0.85, 0.55)) +@ + +\subsection{Position Limit Constraint} +The position limit constraint allows the user to specify limits on the number of assets with non-zero, long, or short positions. The ROI solver interfaces to the Rglpk package (i.e. using the glpk plugin) for solving maximizing return and ETL/ES/cVaR objectives. The Rglpk package supports integer programming and thus supports position limit constraints for the \code{max\_pos} argument. The quadprog package does not support integer programming, and therefore \code{max\_pos} is not supported for the ROI solver using the quadprog plugin. Note that \code{max\_pos\_long} and \code{max\_pos\_short} are not supported for either ROI solver. All position limit constraints are fully supported for DEoptim and random solvers. + +<>= +# Add position limit constraint such that we have a maximum number of three assets with non-zero weights. +pspec <- add.constraint(portfolio=pspec, type="position_limit", max_pos=3) + +# Can also specify maximum number of long positions and short positions +# pspec <- add.constraint(portfolio=pspec, type="position_limit", max_pos_long=3, max_pos_short=3) +@ + +\subsection{Diversification Constraint} +The diversification constraint allows the user to target diversification. Diversification is defined as $diversification = \sum_{i=1}^N w_i^2$ for $N$ assets. The diversification constraint is implemented for the global optimizers by applying a penalty if the diversification value is more than 5\% away from \code{div\_target}. Note that diversification as a constraint is not supported for the ROI solvers, it is only supported for the global numeric solvers. +<<>>= +pspec <- add.constraint(portfolio=pspec, type="diversification", div_target=0.7) +@ + +\subsection{Turnover Constraint} +A target turnover can be specified as a constraint. The turnover is calculated from a set of initial weights. The initial weights can be specified, by default they are the initial weights in the portfolio object. The turnover constraint is implemented for the global optimizers by applying a penalty if the turnover value is more than 5\% away from \code{turnover\_target}. Note that the turnover constraint is not currently supported for quadratic utility and minimum variance problems using the ROI solver. +<<>>= +pspec <- add.constraint(portfolio=pspec, type="turnover", turnover_target=0.2) +@ + +\subsection{Target Return Constraint} +The target return constraint allows the user to specify a target mean return. +<<>>= +pspec <- add.constraint(portfolio=pspec, type="return", return_target=0.007) +@ + +\subsection{Factor Exposure Constraint} +The factor exposure constraint allows the user to set upper and lower bounds on exposures to risk factors. The exposures can be passed in as a vector or matrix. Here we specify a vector for \code{B} with arbitrary values, e.g. betas of the assets, with a market risk exposure range of 0.6 to 0.9. +<>= +pspec <- add.constraint(portfolio=pspec, type="factor_exposure", + B=c(-0.08, 0.37, 0.79, 1.43), + lower=0.6, upper=0.9) +@ + +\subsection{Transaction Cost Constraint} +The transaction cost constraint allows the user to specify proportional transaction costs. Proportional transaction cost constraints can be implemented for quadratic utility and minimum variance problems using the ROI solver. Transaction costs are supported as a penalty for the global numeric solvers. Here we add the transaction cost contraint with the proportional transaction cost value of 1\%. +<<>>= +pspec <- add.constraint(portfolio=pspec, type="transaction_cost", ptc=0.01) +@ + +The print method for the portfolio object shows a concise view of the portfolio and the constraints that have been added. +<<>>= +print(pspec) +@ + +The summary method gives a more detailed view of the constraints. +<<>>= +summary(pspec) +@ + +This demonstrates adding constraints to the portfolio object. As an alternative to adding constraints directly to the portfolio object, constraints can be specified as separate objects. + +\subsection{Specifying Constraints as Separate Objects} +The following examples will demonstrate how to specify constraints as separate objects for all constraints types. + +<>= +# full investment constraint +weight_constr <- weight_sum_constraint(min_sum=1, max_sum=1) + +# box constraint +box_constr <- box_constraint(assets=pspec$assets, min=0, max=1) + +# group constraint +group_constr <- group_constraint(assets=pspec$assets, + groups=list(c(1, 2, 3), + 4), + group_min=c(0.1, 0.15), + group_max=c(0.85, 0.55), + group_labels=c("GroupA", "GroupB")) + +# position limit constraint +poslimit_constr <- position_limit_constraint(assets=pspec$assets, max_pos=3) + +# diversification constraint +div_constr <- diversification_constraint(div_target=0.7) + +# turnover constraint +to_constr <- turnover_constraint(turnover_target=0.2) + +# target return constraint +ret_constr <- return_constraint(return_target=0.007) + +# factor exposure constraint +exp_constr <- factor_exposure_constraint(assets=pspec$assets, + B=c(-0.08, 0.37, 0.79, 1.43), + lower=0.6, upper=0.9) + +# transaction cost constraint +ptc_constr <- transaction_cost_constraint(assets=pspec$assets, ptc=0.01) +@ + +\section{Adding Objectives} +Objectives can be added to the portfolio object with \code{add.objective}. The \code{add.objective} function is the main function for adding and/or updating business objectives to the portfolio object. This function allows the user to specify the \verb"portfolio" to add the objectives to, the \verb"type" (currently 'return', 'risk', 'risk\_budget', or 'weight\_concentration'), \verb"name" of the objective function, \verb"arguments" to the objective function, and whether or not to \verb"enable" the objective. If updating an existing constraint, the \verb"indexnum" argument can be specified. + +\subsection{Portfolio Risk Objective} +The portfolio risk objective allows the user to specify a risk function to minimize +Here we add a risk objective to minimize portfolio expected tail loss with a confidence level of 0.95. Other default arguments to the function can be passed in as a named list to arguments. Note that the name of the function must correspond to a function in R. Many functions are available in the \verb"PerformanceAnalytics" package or a user defined function. +<>= +pspec <- add.objective(portfolio=pspec, + type='risk', + name='ETL', + arguments=list(p=0.95)) +@ + +\subsection{Portfolio Return Objective} +The return objective allows the user to specify a return function to maximize. Here we add a return objective to maximize the portfolio mean return. +<>= +pspec <- add.objective(portfolio=pspec, + type='return', + name='mean') +@ + +\subsection{Portfolio Risk Budget Objective} +The portfolio risk objective allows the user to specify constraints to minimize component contribution (i.e. equal risk contribution) or specify upper and lower bounds on percentage risk contribution. Here we specify that no asset can contribute more than 30\% to total portfolio risk. See the risk budget optimization vignette for more detailed examples of portfolio optimizations with risk budgets. +<>= +pspec <- add.objective(portfolio=pspec, type="risk_budget", name="ETL", + arguments=list(p=0.95), max_prisk=0.3) + +# for an equal risk contribution portfolio, set min_concentration=TRUE +# pspec <- add.objective(portfolio=pspec, type="risk_budget", name="ETL", +# arguments=list(p=0.95), min_concentration=TRUE) +@ + + +\subsection{Portfolio Weight Concentration Objective} +The weight concentration objective allows the user to specify an objective to minimize concentration as measured by the Herfindahl-Hirschman Index. For otpimization problems solved with the global numeric optimizers, the portfolio HHI value is penalized using \code{conc\_aversion} value as the multiplier. + +For quadratic utility problems with weight concentration as an objective using the ROI solver, this is implemented as a penalty to the objective function. The objective function is implemented as follows: + +\begin{eqnarray} +\underset{\boldsymbol{w}}{\text{maximize}} +\boldsymbol{w}' \boldsymbol{\mu} - \frac{\lambda}{2}(\boldsymbol{w}' \boldsymbol{\Sigma} \boldsymbol{w} + \lambda_{hhi} * HHI)\\ +\end{eqnarray} +Where $\mu$ is the estimated mean asset returns, $\lambda$ is the risk aversion parameter, $lambda_{hhi}$ is the concentration aversion parameter, $HHI$ is the portfolio $HHI$, $\boldsymbol{\Sigma}$ is the estimated covariance matrix of asset returns and $\boldsymbol{w}$ is the set of weights. + +Here we add a weight concentration objective for the overall portfolio HHI. +<>= +pspec <- add.objective(portfolio=pspec, type="weight_concentration", + name="HHI", conc_aversion=0.1) +@ + +The weight concentration aversion parameter by groups can also be specified. Here we add a weight concentration objective specifying groups and concentration aversion parameters by group. +<>= +pspec <- add.objective(portfolio=pspec, type="weight_concentration", + name="HHI", + conc_aversion=c(0.03, 0.06), + conc_groups=list(c(1, 2), + c(3, 4))) +@ + +The print method for the portfolio object will now show all the constraints and objectives that have been added. +<<>>= +print(pspec) +@ + +The \code{summary} function gives a more detailed view. +<<>>= +summary(pspec) +@ + +\section{Solvers} +The PortfolioAnalytics package currently supports random portfolios, DEoptim, pso, GenSA, and ROI as back ends. Note that some of the QP/LP problems are solved directly with Rglpk and quadprog. The solver can be specified with the \code{optimize\_method} argument in \code{optimize.portfolio} and \code{optimize.portfolio.rebalancing}. + +\subsection{DEoptim} +PortfolioAnalytics uses the \code{DEoptim} function from the R package \verb"DEoptim". Differential evolution is a stochastic global optimization algorithm. See \code{?DEoptim} and the references contained therein for more information. See also \href{http://cran.r-project.org/web/packages/DEoptim/vignettes/DEoptimPortfolioOptimization.pdf}{Large scale portfolio optimization with DEoptim}. +\subsection{Random Portfolios} +PortfolioAnalytics has three methods to generate random portfolios. +\begin{enumerate} +\item The 'sample' method to generate random portfolios is based on an idea by Pat Burns. This is the most flexible method, but also the slowest, and can generate portfolios to satisfy leverage, box, group, and position limit constraints. +\item The 'simplex' method to generate random portfolios is based on a paper by W. T. Shaw. The simplex method is useful to generate random portfolios with the full investment constraint, where the sum of the weights is equal to 1, and min box constraints. Values for \code{min\_sum} and \code{max\_sum} of the leverage constraint will be ignored, the sum of weights will equal 1. All other constraints such as the box constraint max, group and position limit constraints will be handled by elimination. If the constraints are very restrictive, this may result in very few feasible portfolios remaining. Another key point to note is that the solution may not be along the vertexes depending on the objective. For example, a risk budget objective will likely place the portfolio somewhere on the interior. +\item The 'grid' method to generate random portfolios is based on the \code{gridSearch} function in package \verb"NMOF". The grid search method only satisfies the \code{min} and \code{max} box constraints. The \code{min\_sum} and \code{max\_sum} leverage constraint will likely be violated and the weights in the random portfolios should be normalized. Normalization may cause the box constraints to be violated and will be penalized in \code{constrained\_objective}. +\end{enumerate} + +The following plots illustrate the various methods to generate random portfolios. + +<>= +R <- edhec[, 1:4] + +# set up simple portfolio with leverage and box constraints +pspec <- portfolio.spec(assets=colnames(R)) +pspec <- add.constraint(portfolio=pspec, type="leverage", + min_sum=0.99, max_sum=1.01) +pspec <- add.constraint(portfolio=pspec, type="box", min=0, max=1) + +# generate random portfolios using the 3 methods +rp1 <- random_portfolios(portfolio=pspec, permutations=5000, + rp_method='sample') +rp2 <- random_portfolios(portfolio=pspec, permutations=5000, + rp_method='simplex') +rp3 <- random_portfolios(portfolio=pspec, permutations=5000, + rp_method='grid') + +# show feasible portfolios in mean-StdDev space +tmp1.mean <- apply(rp1, 1, function(x) mean(R %*% x)) +tmp1.StdDev <- apply(rp1, 1, function(x) StdDev(R=R, weights=x)) +tmp2.mean <- apply(rp2, 1, function(x) mean(R %*% x)) +tmp2.StdDev <- apply(rp2, 1, function(x) StdDev(R=R, weights=x)) +tmp3.mean <- apply(rp3, 1, function(x) mean(R %*% x)) +tmp3.StdDev <- apply(rp3, 1, function(x) StdDev(R=R, weights=x)) + +# plot feasible portfolios +plot(x=tmp1.StdDev, y=tmp1.mean, col="gray", main="Random Portfolio Methods", + ylab="mean", xlab="StdDev") +points(x=tmp2.StdDev, y=tmp2.mean, col="red", pch=2) +points(x=tmp3.StdDev, y=tmp3.mean, col="lightgreen", pch=5) +legend("bottomright", legend=c("sample", "simplex", "grid"), + col=c("gray", "red", "lightgreen"), + pch=c(1, 2, 5), bty="n") +@ + +Figure 1 shows the feasible space using the different random portfolio methods. The 'sample' method has relatively even coverage of the feasible space. The 'simplex' method also has relatively even coverage of the space, but it is also more concentrated around the assets. The 'grid' method is pushed to the interior of the space due to the normalization. + +The \code{fev} argument controls the face-edge-vertex biasing. Higher values for \code{fev} will result in the weights vector more concentrated on a single asset. This can be seen in the following charts. +<>= +fev <- 0:5 +par(mfrow=c(2, 3)) +for(i in 1:length(fev)){ + rp <- rp_simplex(portfolio=pspec, permutations=2000, fev=fev[i]) + tmp.mean <- apply(rp, 1, function(x) mean(R %*% x)) + tmp.StdDev <- apply(rp, 1, function(x) StdDev(R=R, weights=x)) + plot(x=tmp.StdDev, y=tmp.mean, main=paste("FEV =", fev[i]), + ylab="mean", xlab="StdDev", col=rgb(0, 0, 100, 50, maxColorValue=255)) +} +par(mfrow=c(1,1)) +@ + +Figure 2 shows the feasible space varying the fev values. + +The \code{fev} argument can be passed in as a vector for more control over the coverage of the feasible space. The default value is \code{fev=0:5}. +<>= +par(mfrow=c(1, 2)) +# simplex +rp_simplex <- random_portfolios(portfolio=pspec, permutations=2000, + rp_method='simplex') +tmp.mean <- apply(rp_simplex, 1, function(x) mean(R %*% x)) +tmp.StdDev <- apply(rp_simplex, 1, function(x) StdDev(R=R, weights=x)) +plot(x=tmp.StdDev, y=tmp.mean, main="rp_method=simplex fev=0:5", + ylab="mean", xlab="StdDev", col=rgb(0, 0, 100, 50, maxColorValue=255)) +#sample +rp_sample <- random_portfolios(portfolio=pspec, permutations=2000, + rp_method='sample') +tmp.mean <- apply(rp_sample, 1, function(x) mean(R %*% x)) +tmp.StdDev <- apply(rp_sample, 1, function(x) StdDev(R=R, weights=x)) +plot(x=tmp.StdDev, y=tmp.mean, main="rp_method=sample", + ylab="mean", xlab="StdDev", col=rgb(0, 0, 100, 50, maxColorValue=255)) +par(mfrow=c(1,1)) +@ + +\subsection{pso} +PortfolioAnalytics uses the \code{psoptim} function from the R package \verb"pso". Particle swarm optimization is a heuristic optimization algorithm. See \code{?psoptim} and the references contained therein for more information. + +\subsection{GenSA} +PortfolioAnalytics uses the \code{GenSA} function from the R package \verb"GenSA". Generalized simmulated annealing is generic probabilistic heuristic optimization algorithm. See \code{?GenSA} and the references contained therein for more information. + +\subsection{ROI} +The \verb"ROI" package serves as an interface to the \verb"Rglpk" package and the \verb"quadprog" package to solve linear and quadratic programming problems. The interface to the \verb"ROI" package solves a limited type of convex optimization problems: + +\begin{enumerate} +\item Maxmimize portfolio return subject leverage, box, group, position limit, target mean return, and/or factor exposure constraints on weights. +\item Minimize portfolio variance subject to leverage, box, group, turnover, and/or factor exposure constraints (otherwise known as global minimum variance portfolio). +\item Minimize portfolio variance subject to leverage, box, group, and/or factor exposure constraints and a desired portfolio return. +\item Maximize quadratic utility subject to leverage, box, group, target mean return, turnover, and/or factor exposure constraints and risk aversion parameter. +(The risk aversion parameter is passed into \code{optimize.portfolio} as an added argument to the \code{portfolio} object). +\item Minimize ETL subject to leverage, box, group, position limit, target mean return, and/or factor exposure constraints and target portfolio return. +\end{enumerate} + + +\section{Optimization} +The previous sections demonstrated how to specify a portfolio object, add constraints, add objectives, and the solvers available. This section will demonstrate run the optimizations via \code{optimize.portfolio}. Only a small number of examples will be shown here, see the demos for several more examples. + +\subsection{Initial Portfolio Object} +<<>>= +library(DEoptim) +library(ROI) +require(ROI.plugin.glpk) +require(ROI.plugin.quadprog) + +data(edhec) +R <- edhec[, 1:6] +colnames(R) <- c("CA", "CTAG", "DS", "EM", "EQMN", "ED") +funds <- colnames(R) + +# Create an initial portfolio object with leverage and box constraints +init <- portfolio.spec(assets=funds) +init <- add.constraint(portfolio=init, type="leverage", + min_sum=0.99, max_sum=1.01) +init <- add.constraint(portfolio=init, type="box", min=0.05, max=0.65) +@ + +\subsection{Maximize mean return with ROI} +Add an objective to maximize mean return. +<<>>= +maxret <- add.objective(portfolio=init, type="return", name="mean") +@ + +Run the optimization. +<>= +opt_maxret <- optimize.portfolio(R=R, portfolio=maxret, + optimize_method="ROI", + trace=TRUE) + +print(opt_maxret) +@ + +Chart the weights and optimal portfolio in risk-return space. The weights and a risk-reward scatter plot can be plotted separately as shown below with the \code{chart.Weights} and \code{chart.RiskReward} functions. The \code{plot} function will plot the weights and risk-reward scatter together. +<>= +plot(opt_maxret, risk.col="StdDev", return.col="mean", + main="Maximum Return Optimization", chart.assets=TRUE, + xlim=c(0, 0.05), ylim=c(0,0.0085)) +@ + +\subsection{Minimize variance with ROI} +Add an objective to minimize portfolio variance. +<<>>= +minvar <- add.objective(portfolio=init, type="risk", name="var") +@ + +Run the optimization. Note that although 'var' is the risk metric, 'StdDev' is returned as an objective measure. +<>= +opt_minvar <- optimize.portfolio(R=R, portfolio=minvar, + optimize_method="ROI", trace=TRUE) +print(opt_minvar) +@ + +Chart the weights and optimal portfolio in risk-return space. +<>= +plot(opt_minvar, risk.col="StdDev", return.col="mean", + main="Minimum Variance Optimization", chart.assets=TRUE, + xlim=c(0, 0.05), ylim=c(0,0.0085)) +@ + +\subsection{Maximize quadratic utility with ROI} +Add mean and var objectives for quadratic utility. Note that the risk aversion parameter for quadratic utility is specifed in the objective as shown below. +<<>>= +qu <- add.objective(portfolio=init, type="return", name="mean") +qu <- add.objective(portfolio=qu, type="risk", name="var", risk_aversion=0.25) +@ + +Run the optimization. +<>= +opt_qu <- optimize.portfolio(R=R, portfolio=qu, + optimize_method="ROI", + trace=TRUE) +print(opt_qu) +@ + +<>= +plot(opt_qu, risk.col="StdDev", return.col="mean", + main="Quadratic Utility Optimization", chart.assets=TRUE, + xlim=c(0, 0.05), ylim=c(0, 0.0085)) +@ + +\subsection{Minimize expected tail loss with ROI} +Add ETL objective. +<<>>= +etl <- add.objective(portfolio=init, type="risk", name="ETL") +@ + +Run the optimization. +<>= +opt_etl <- optimize.portfolio(R=R, portfolio=etl, + optimize_method="ROI", + trace=TRUE) +print(opt_etl) +@ + +<>= +plot(opt_etl, risk.col="ES", return.col="mean", + main="ETL Optimization", chart.assets=TRUE, + xlim=c(0, 0.14), ylim=c(0,0.0085)) +@ + +\subsection{Maximize mean return per unit ETL with random portfolios} +Add mean and ETL objectives. +<>= +meanETL <- add.objective(portfolio=init, type="return", name="mean") +meanETL <- add.objective(portfolio=meanETL, type="risk", name="ETL", + arguments=list(p=0.95)) +@ + +Run the optimization. The default random portfolio method is 'sample'. +<>= +opt_meanETL <- optimize.portfolio(R=R, portfolio=meanETL, + optimize_method="random", + trace=TRUE, search_size=2000) +print(opt_meanETL) +@ + +The optimization was run with \code{trace=TRUE} so that iterations and other output from random portfolios is stored in the \code{opt\_meanETL} object. The \code{extractStats} function can be used to get a matrix of the weights and objective measures at each iteration. +<<>>= +stats_meanETL <- extractStats(opt_meanETL) +dim(stats_meanETL) +head(stats_meanETL) +@ + +Chart the optimal weights and optimal portfolio in risk-return space. Because the optimization was run with \code{trace=TRUE}, the chart of the optimal portfolio also includes the trace portfolios of the optimization. This is usefule to visualize the feasible space of the portfolios. The 'neighbor' portfolios relative to the optimal portfolio weights can be included the chart of the optimal weights. +<>= +plot(opt_meanETL, risk.col="ETL", return.col="mean", + main="mean-ETL Optimization", neighbors=25) +@ + +Calculate and plot the portfolio component ETL contribution. +<>= +pct_contrib <- ES(R=R, p=0.95, portfolio_method="component", + weights=extractWeights(opt_meanETL)) +barplot(pct_contrib$pct_contrib_MES, cex.names=0.8, las=3, col="lightblue") +@ + +This figure shows that the Equity Market Nuetral strategy has greater than 50\% risk contribution. A risk budget objective can be added to limit risk contribution percentage to 40\%. + +\subsection{Maximize mean return per unit ETL with ETL risk budgets} +Add objectives to maximize mean return per unit ETL with 40\% limit ETL risk budgets. +<>= +# change the box constraints to long only +init$constraints[[2]]$min <- rep(0, 6) +init$constraints[[2]]$max <- rep(1, 6) + +rb_meanETL <- add.objective(portfolio=init, type="return", name="mean") +rb_meanETL <- add.objective(portfolio=rb_meanETL, type="risk", name="ETL", + arguments=list(p=0.95)) [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3625 From noreply at r-forge.r-project.org Tue Mar 24 00:54:53 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 24 Mar 2015 00:54:53 +0100 (CET) Subject: [Returnanalytics-commits] r3626 - pkg/PerformanceAnalytics/R Message-ID: <20150323235453.681B6185DD8@r-forge.r-project.org> Author: peter_carl Date: 2015-03-24 00:54:52 +0100 (Tue, 24 Mar 2015) New Revision: 3626 Modified: pkg/PerformanceAnalytics/R/DrawdownPeak.R pkg/PerformanceAnalytics/R/Drawdowns.R pkg/PerformanceAnalytics/R/chart.Drawdown.R Log: - removing DrawdownPeak from namespace - re-adding Drawdowns to namespace with alias to chart.Drawdown Modified: pkg/PerformanceAnalytics/R/DrawdownPeak.R =================================================================== --- pkg/PerformanceAnalytics/R/DrawdownPeak.R 2015-03-22 07:08:55 UTC (rev 3625) +++ pkg/PerformanceAnalytics/R/DrawdownPeak.R 2015-03-23 23:54:52 UTC (rev 3626) @@ -9,7 +9,7 @@ #' @author Matthieu Lestel #' ###keywords ts multivariate distribution models -#' @export +### #' @export DrawdownPeak <- function (R, ...) { Modified: pkg/PerformanceAnalytics/R/Drawdowns.R =================================================================== --- pkg/PerformanceAnalytics/R/Drawdowns.R 2015-03-22 07:08:55 UTC (rev 3625) +++ pkg/PerformanceAnalytics/R/Drawdowns.R 2015-03-23 23:54:52 UTC (rev 3626) @@ -1,3 +1,5 @@ +#' @export + Drawdowns <- function (R, geometric = TRUE, ...) { # @author Peter Carl Modified: pkg/PerformanceAnalytics/R/chart.Drawdown.R =================================================================== --- pkg/PerformanceAnalytics/R/chart.Drawdown.R 2015-03-22 07:08:55 UTC (rev 3625) +++ pkg/PerformanceAnalytics/R/chart.Drawdown.R 2015-03-23 23:54:52 UTC (rev 3626) @@ -32,7 +32,7 @@ #' chart.Drawdown(edhec[,c(1,2)], #' main="Drawdown from Peak Equity Attained", #' legend.loc="bottomleft") -#' +#' @aliases Drawdowns #' @export chart.Drawdown <- function (R, geometric = TRUE, legend.loc = NULL, colorset = (1:12), ...) From noreply at r-forge.r-project.org Wed Mar 25 14:16:56 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 25 Mar 2015 14:16:56 +0100 (CET) Subject: [Returnanalytics-commits] r3627 - pkg/PerformanceAnalytics/R Message-ID: <20150325131656.7868618656A@r-forge.r-project.org> Author: peter_carl Date: 2015-03-25 14:16:56 +0100 (Wed, 25 Mar 2015) New Revision: 3627 Modified: pkg/PerformanceAnalytics/R/chart.ACFplus.R Log: - replaces standard plot with barplot for easier reading Modified: pkg/PerformanceAnalytics/R/chart.ACFplus.R =================================================================== --- pkg/PerformanceAnalytics/R/chart.ACFplus.R 2015-03-23 23:54:52 UTC (rev 3626) +++ pkg/PerformanceAnalytics/R/chart.ACFplus.R 2015-03-25 13:16:56 UTC (rev 3627) @@ -29,7 +29,7 @@ if (is.null(maxlag)) maxlag = ceiling(10 + sqrt(num)) ACF = acf(data, maxlag, plot = FALSE)$acf[-1] - PACF = pacf(data, maxlag, plot = FALSE)$acf + PACF = t(as.matrix(pacf(data, maxlag, plot = FALSE)$acf)) Lag = 1:length(ACF)/frequency(data) minA = min(ACF) minP = min(PACF) @@ -47,16 +47,16 @@ # ACF chart par(mar=c(0.5,4,4,2) + 0.1) - plot(Lag, ACF, type = "h", ylim = c(minu,1), main = main, axes = FALSE, ...) + barplot(ACF, ylim = c(minu,1), main = main, axes = FALSE, ylab="acf", ...) box(col=elementcolor) axis(2, col = elementcolor, cex.axis = 0.8) abline(h=c(0,L,U), lty=c(1,2,2), col=c(1,4,4)) # PACF chart par(mar=c(4,4,0.5,2)+ 0.1) - plot(Lag, PACF, type = "h", ylim = c(minu,1), axes = FALSE, ...) + barplot(PACF, ylim = c(minu,1), axes = FALSE, ylab="pacf", ...) box(col=elementcolor) - axis(1, col = elementcolor, cex.axis = 0.8) + axis(1, col = elementcolor, cex.axis = 0.8, xlab="lag") axis(2, col = elementcolor, cex.axis = 0.8) abline(h=c(0,L,U), lty=c(1,2,2), col=c(1,4,4))