From noreply at r-forge.r-project.org Mon Feb 10 00:55:33 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 10 Feb 2014 00:55:33 +0100 (CET) Subject: [Returnanalytics-commits] r3306 - in pkg/PortfolioAnalytics: . R man Message-ID: <20140209235533.C4AC4186A39@r-forge.r-project.org> Author: rossbennett34 Date: 2014-02-10 00:55:31 +0100 (Mon, 10 Feb 2014) New Revision: 3306 Added: pkg/PortfolioAnalytics/man/print.optimize.portfolio.rebalancing.Rd pkg/PortfolioAnalytics/man/print.summary.optimize.portfolio.rebalancing.Rd Modified: pkg/PortfolioAnalytics/NAMESPACE pkg/PortfolioAnalytics/R/charts.risk.R pkg/PortfolioAnalytics/R/extractstats.R pkg/PortfolioAnalytics/R/generics.R pkg/PortfolioAnalytics/R/optimize.portfolio.R Log: modifying optimize.portfolio.rebalancing and associated functions/methods for improved output Modified: pkg/PortfolioAnalytics/NAMESPACE =================================================================== --- pkg/PortfolioAnalytics/NAMESPACE 2014-01-28 23:30:50 UTC (rev 3305) +++ pkg/PortfolioAnalytics/NAMESPACE 2014-02-09 23:55:31 UTC (rev 3306) @@ -100,6 +100,7 @@ S3method(extractObjectiveMeasures,opt.list) S3method(extractObjectiveMeasures,optimize.portfolio.rebalancing) S3method(extractObjectiveMeasures,optimize.portfolio) +S3method(extractObjectiveMeasures,summary.optimize.portfolio.rebalancing) S3method(extractStats,optimize.portfolio.DEoptim) S3method(extractStats,optimize.portfolio.eqwt) S3method(extractStats,optimize.portfolio.GenSA) @@ -112,6 +113,7 @@ S3method(extractWeights,opt.list) S3method(extractWeights,optimize.portfolio.rebalancing) S3method(extractWeights,optimize.portfolio) +S3method(extractWeights,summary.optimize.portfolio.rebalancing) S3method(plot,optimize.portfolio.DEoptim) S3method(plot,optimize.portfolio.GenSA) S3method(plot,optimize.portfolio.pso) @@ -124,8 +126,10 @@ S3method(print,optimize.portfolio.GenSA) S3method(print,optimize.portfolio.pso) S3method(print,optimize.portfolio.random) +S3method(print,optimize.portfolio.rebalancing) S3method(print,optimize.portfolio.ROI) S3method(print,portfolio) +S3method(print,summary.optimize.portfolio.rebalancing) S3method(print,summary.optimize.portfolio) S3method(summary,efficient.frontier) S3method(summary,optimize.portfolio.rebalancing) Modified: pkg/PortfolioAnalytics/R/charts.risk.R =================================================================== --- pkg/PortfolioAnalytics/R/charts.risk.R 2014-01-28 23:30:50 UTC (rev 3305) +++ pkg/PortfolioAnalytics/R/charts.risk.R 2014-02-09 23:55:31 UTC (rev 3306) @@ -218,7 +218,7 @@ rebal.obj <- extractObjectiveMeasures(object) if(risk.type == "absolute"){ - rbcols <- grep(paste(match.col, "pct_contrib", sep="."), colnames(rebal.obj)) + rbcols <- grep(paste(match.col, "contribution", sep="."), colnames(rebal.obj)) if(length(rbcols) < 1) stop(paste("No ", match.col, ".contribution columns.", sep="")) rbdata <- rebal.obj[, rbcols] chart.StackedBar(w=rbdata, ylab=paste(match.col, "Contribution", sep=" "), main=main, ...) Modified: pkg/PortfolioAnalytics/R/extractstats.R =================================================================== --- pkg/PortfolioAnalytics/R/extractstats.R 2014-01-28 23:30:50 UTC (rev 3305) +++ pkg/PortfolioAnalytics/R/extractstats.R 2014-02-09 23:55:31 UTC (rev 3306) @@ -194,21 +194,27 @@ if(!inherits(object, "optimize.portfolio.rebalancing")){ stop("Object passed in must be of class 'optimize.portfolio.rebalancing'") } - - numColumns = length(object[[1]]$weights) - numRows = length(object) + rebal_object <- object$opt_rebal + numColumns = length(rebal_object[[1]]$weights) + numRows = length(rebal_object) result <- matrix(nrow=numRows, ncol=numColumns) for(i in 1:numRows) - result[i,] = unlist(object[[i]]$weights) + result[i,] = unlist(rebal_object[[i]]$weights) - colnames(result) = names(unlist(object[[1]]$weights)) - rownames(result) = names(object) + colnames(result) = names(unlist(rebal_object[[1]]$weights)) + rownames(result) = names(rebal_object) result = as.xts(result) return(result) } +#' @method extractWeights summary.optimize.portfolio.rebalancing +#' @S3method extractWeights summary.optimize.portfolio.rebalancing +#' @export +extractWeights.summary.optimize.portfolio.rebalancing <- function(object, ...){ + object$weights +} #' @method extractStats optimize.portfolio.ROI #' @S3method extractStats optimize.portfolio.ROI @@ -350,7 +356,7 @@ #' @export extractStats.optimize.portfolio.rebalancing <- function(object, prefix=NULL, ...) { if(!inherits(object, "optimize.portfolio.rebalancing")) stop("object must be of class optimize.portfolio.rebalancing") - return(lapply(object, extractStats, ...)) + return(lapply(object$opt_rebal, extractStats, ...)) } #' Extract the objective measures @@ -381,21 +387,29 @@ extractObjectiveMeasures.optimize.portfolio.rebalancing <- function(object){ if(!inherits(object, "optimize.portfolio.rebalancing")) stop("object must be of class 'optimize.portfolio.rebalancing'") - num.columns <- length(unlist(extractObjectiveMeasures(object[[1]]))) - num.rows <- length(object) + rebal_object <- object$opt_rebal + num.columns <- length(unlist(extractObjectiveMeasures(rebal_object[[1]]))) + num.rows <- length(rebal_object) + result <- matrix(nrow=num.rows, ncol=num.columns) for(i in 1:num.rows){ - result[i,] <- unlist(extractObjectiveMeasures(object[[i]])) + result[i,] <- unlist(extractObjectiveMeasures(rebal_object[[i]])) } - colnames(result) <- name.replace(names(unlist(extractObjectiveMeasures(object[[1]])))) - rownames(result) <- names(object) + colnames(result) <- name.replace(names(unlist(extractObjectiveMeasures(rebal_object[[1]])))) + rownames(result) <- names(rebal_object) result <- as.xts(result) return(result) } +#' @method extractObjectiveMeasures summary.optimize.portfolio.rebalancing +#' @S3method extractObjectiveMeasures summary.optimize.portfolio.rebalancing +extractObjectiveMeasures.summary.optimize.portfolio.rebalancing <- function(object){ + object$objective_measures +} + #' Extract the group and/or category weights #' #' This function extracts the weights by group and/or category from an object Modified: pkg/PortfolioAnalytics/R/generics.R =================================================================== --- pkg/PortfolioAnalytics/R/generics.R 2014-01-28 23:30:50 UTC (rev 3305) +++ pkg/PortfolioAnalytics/R/generics.R 2014-02-09 23:55:31 UTC (rev 3306) @@ -10,6 +10,47 @@ # ############################################################################### +#' Printing output of optimize.portfolio.rebalancing +#' +#' print method for \code{optimize.portfolio.rebalancing} objects +#' +#' @param x an object used to select a method +#' @param \dots any other passthru parameters +#' @param digits the number of significant digits to use when printing. +#' @seealso \code{\link{optimize.portfolio.rebalancing}} +#' @author Ross Bennett +#' @rdname print.optimize.portfolio.rebalancing +#' @method print optimize.portfolio.rebalancing +#' @S3method print optimize.portfolio.rebalancing +print.optimize.portfolio.rebalancing <- function(x, ..., digits=4){ + cat(rep("*", 50) ,"\n", sep="") + cat("PortfolioAnalytics Optimization with Rebalancing\n") + cat(rep("*", 50) ,"\n", sep="") + + cat("\nCall:\n", paste(deparse(x$call), sep = "\n", collapse = "\n"), + "\n\n", sep = "") + + tmp_summary <- summary(x) + rebal_dates <- tmp_summary$rebalance_dates + num_dates <- length(rebal_dates) + cat("Number of rebalancing dates: ", num_dates, "\n") + + cat("First rebalance date:\n") + print(rebal_dates[1]) + + cat("Last rebalance date:\n") + print(rebal_dates[num_dates]) + + cat("\n") + cat("Annualized Portfolio Rebalancing Return:\n") + print(as.numeric(tmp_summary$annualized_returns)) + cat("\n") + + cat("Annualized Portfolio Standard Deviation:\n") + print(as.numeric(tmp_summary$annualized_StdDev)) + cat("\n") +} + #' summary method for optimize.portfolio.rebalancing #' @param object object of type optimize.portfolio.rebalancing #' @param \dots any other passthru parameters @@ -18,29 +59,85 @@ summary.optimize.portfolio.rebalancing <- function(object, ...) { if(!inherits(object,"optimize.portfolio.rebalancing")) stop ("passed object is not of class optimize.portfolio.rebalancing") + call <- object$call + elapsed_time <- object$elapsed_time + # Extract the weights and objective measures + weights <- extractWeights(object) + rebalance_dates <- index(weights) + objective_measures <- extractObjectiveMeasures(object) - # loop through and show the results and weights - cat('Weights:\n') - for(i in 1:length(object)){ - cat(names(object[i])) - cat('\n') - if(!inherits(object[i],'try-error')){ - print(round(object[[i]]$weights,4)) - } else { - print(object[i]) - } - } - cat('Objective Measures\n') - for(i in 1:length(object)){ - if(!inherits(object[i],'try-error')){ - cat(names(object[i])) - cat('\n') - print(object[[i]]$constrained_objective) - } - } + # Calculate the portfolio rebalancing returns and some useful + # performance metrics + portfolio_returns <- Return.rebalancing(object$R, weights) + annualized_returns <- Return.annualized(portfolio_returns) + annualized_StdDev <- StdDev.annualized(portfolio_returns) + downside_risk <- table.DownsideRisk(portfolio_returns) + + # Structure and return + return(structure(list(weights=weights, + objective_measures=objective_measures, + portfolio_returns=portfolio_returns, + annualized_returns=annualized_returns, + annualized_StdDev=annualized_StdDev, + downside_risk=downside_risk, + rebalance_dates=rebalance_dates, + call=call, + elapsed_time=elapsed_time), + class="summary.optimize.portfolio.rebalancing") + ) } +#' Printing summary output of optimize.portfolio.rebalancing +#' +#' print method for objects of class \code{summary.optimize.portfolio.rebalancing} +#' +#' @param x an object of class \code{summary.optimize.portfolio.rebalancing}. +#' @param ... any other passthru parameters +#' @param digits number of digits used for printing +#' @seealso \code{\link{summary.optimize.portfolio.rebalancing}} +#' @author Ross Bennett +#' @method print summary.optimize.portfolio.rebalancing +#' @S3method print summary.optimize.portfolio.rebalancing +print.summary.optimize.portfolio.rebalancing <- function(x, ..., digits=4){ + cat(rep("*", 50) ,"\n", sep="") + cat("PortfolioAnalytics Optimization with Rebalancing\n") + cat(rep("*", 50) ,"\n", sep="") + + cat("\nCall:\n", paste(deparse(x$call), sep = "\n", collapse = "\n"), + "\n\n", sep = "") + + rebal_dates <- x$rebalance_dates + num_dates <- length(rebal_dates) + cat("First rebalance date:\n") + print(rebal_dates[1]) + cat("\n") + cat("Last rebalance date:\n") + print(rebal_dates[num_dates]) + cat("\n") + + cat("Annualized Portfolio Rebalancing Return:\n") + print(as.numeric(x$annualized_returns)) + cat("\n") + + cat("Annualized Portfolio Standard Deviation:\n") + print(as.numeric(x$annualized_StdDev)) + cat("\n") + + cat("Downside Risk Measures:\n") + print(x$downside_risk, ...=...) + + # Should we include the optimal weights and objective measure values on the + # first or last rebalance date? + # cat("Optimal weights on first rebalance date:\n") + # print(round(first(x$weights), digits=digits), digits=digits) + # cat("\n") + + # cat("Objective measures on first rebalance date:\n") + # print(round(first(x$objective_measures), digits=digits), digits=digits) + # cat("\n") +} + #' Printing Portfolio Specification Objects #' #' Print method for objects of class \code{portfolio} created with \code{\link{portfolio.spec}} Modified: pkg/PortfolioAnalytics/R/optimize.portfolio.R =================================================================== --- pkg/PortfolioAnalytics/R/optimize.portfolio.R 2014-01-28 23:30:50 UTC (rev 3305) +++ pkg/PortfolioAnalytics/R/optimize.portfolio.R 2014-02-09 23:55:31 UTC (rev 3306) @@ -1245,6 +1245,10 @@ { stopifnot("package:foreach" %in% search() || require("foreach",quietly=TRUE)) stopifnot("package:iterators" %in% search() || require("iterators",quietly=TRUE)) + + # Store the call to return later + call <- match.call() + start_t<-Sys.time() if (!is.null(portfolio) & !is.portfolio(portfolio)){ @@ -1298,12 +1302,24 @@ optimize.portfolio(R[(ifelse(ep-trailing_periods>=1,ep-trailing_periods,1)):ep,], portfolio=portfolio, optimize_method=optimize_method, search_size=search_size, trace=trace, rp=rp, parallel=FALSE, ...=...) } } + # out_list is a list where each element is an optimize.portfolio object + # at each rebalance date names(out_list)<-index(R[ep.i]) - end_t<-Sys.time() - message(c("overall elapsed time:",end_t-start_t)) - class(out_list)<-c("optimize.portfolio.rebalancing") - return(out_list) + end_t <- Sys.time() + # message(c("overall elapsed time:",end_t-start_t)) + elapsed_time <- end_t - start_t + + # out object to return + out <- list() + out$portfolio <- portfolio + out$R <- R + out$call <- call + out$elapsed_time <- elapsed_time + out$opt_rebalancing <- out_list + + class(out) <- c("optimize.portfolio.rebalancing") + return(out) } #'execute multiple optimize.portfolio calls, presumably in parallel Added: pkg/PortfolioAnalytics/man/print.optimize.portfolio.rebalancing.Rd =================================================================== --- pkg/PortfolioAnalytics/man/print.optimize.portfolio.rebalancing.Rd (rev 0) +++ pkg/PortfolioAnalytics/man/print.optimize.portfolio.rebalancing.Rd 2014-02-09 23:55:31 UTC (rev 3306) @@ -0,0 +1,26 @@ +\name{print.optimize.portfolio.rebalancing} +\alias{print.optimize.portfolio.rebalancing} +\title{Printing output of optimize.portfolio.rebalancing} +\usage{ + \method{print}{optimize.portfolio.rebalancing} (x, ..., + digits = 4) +} +\arguments{ + \item{x}{an object used to select a method} + + \item{\dots}{any other passthru parameters} + + \item{digits}{the number of significant digits to use + when printing.} +} +\description{ + print method for \code{optimize.portfolio.rebalancing} + objects +} +\author{ + Ross Bennett +} +\seealso{ + \code{\link{optimize.portfolio.rebalancing}} +} + Added: pkg/PortfolioAnalytics/man/print.summary.optimize.portfolio.rebalancing.Rd =================================================================== --- pkg/PortfolioAnalytics/man/print.summary.optimize.portfolio.rebalancing.Rd (rev 0) +++ pkg/PortfolioAnalytics/man/print.summary.optimize.portfolio.rebalancing.Rd 2014-02-09 23:55:31 UTC (rev 3306) @@ -0,0 +1,26 @@ +\name{print.summary.optimize.portfolio.rebalancing} +\alias{print.summary.optimize.portfolio.rebalancing} +\title{Printing summary output of optimize.portfolio.rebalancing} +\usage{ + \method{print}{summary.optimize.portfolio.rebalancing} + (x, ..., digits = 4) +} +\arguments{ + \item{x}{an object of class + \code{summary.optimize.portfolio.rebalancing}.} + + \item{...}{any other passthru parameters} + + \item{digits}{number of digits used for printing} +} +\description{ + print method for objects of class + \code{summary.optimize.portfolio.rebalancing} +} +\author{ + Ross Bennett +} +\seealso{ + \code{\link{summary.optimize.portfolio.rebalancing}} +} + From noreply at r-forge.r-project.org Mon Feb 10 01:06:24 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 10 Feb 2014 01:06:24 +0100 (CET) Subject: [Returnanalytics-commits] r3307 - pkg/PortfolioAnalytics/demo Message-ID: <20140210000624.A2C69186B7D@r-forge.r-project.org> Author: rossbennett34 Date: 2014-02-10 01:06:24 +0100 (Mon, 10 Feb 2014) New Revision: 3307 Added: pkg/PortfolioAnalytics/demo/risk_budget_backtesting.R Modified: pkg/PortfolioAnalytics/demo/00Index Log: Adding demo for optimize.portfolio.rebalancing Modified: pkg/PortfolioAnalytics/demo/00Index =================================================================== --- pkg/PortfolioAnalytics/demo/00Index 2014-02-09 23:55:31 UTC (rev 3306) +++ pkg/PortfolioAnalytics/demo/00Index 2014-02-10 00:06:24 UTC (rev 3307) @@ -24,5 +24,6 @@ demo_min_StdDev Demonstrate objective to minimize portfolio standard deviation. demo_min_expected_shortfall Demonstrate objective to minimize expected shortfall. demo_risk_budgets Demonstrate using risk budget objectives. -demo_roi_solvers Demonstrate specifying a solver using ROI +demo_roi_solvers Demonstrate specifying a solver using ROI. +risk_budget_backtesting Demonstrate optimize.portfolio.rebalancing with standard deviation risk budget objective. Added: pkg/PortfolioAnalytics/demo/risk_budget_backtesting.R =================================================================== --- pkg/PortfolioAnalytics/demo/risk_budget_backtesting.R (rev 0) +++ pkg/PortfolioAnalytics/demo/risk_budget_backtesting.R 2014-02-10 00:06:24 UTC (rev 3307) @@ -0,0 +1,59 @@ + +library(PortfolioAnalytics) +data(edhec) + +# Use first four columns of edhec data set +R <- edhec[, 1:4] +funds <- colnames(R) + +# Initialize portfolio and add basic constraints +init.portf <- portfolio.spec(funds, weight_seq=generatesequence(min=0, max=1, by=0.002)) +init.portf <- add.constraint(init.portf, "weight_sum")#, min_sum=0.99, max_sum=1.01) +init.portf <- add.constraint(init.portf, "box", min=0, max=0.65) + +# Add mean return objective with multiplier=0 so it is calculated, but does +# not affect optimization +init.portf <- add.objective(init.portf, type="return", name="mean", multiplier=0) + +# Add objective to minimize portfolio standard deviation +SDRB.portf <- add.objective(init.portf, type="risk", name="StdDev") + +# Add StdDev risk budget objective for maximum percentage risk +SDRB.portf <- add.objective(SDRB.portf, type="risk_budget", name="StdDev", max_prisk=0.4) + +# Generate random portfolios +rp <- random_portfolios(init.portf, 5000) + +# Run out of sample backtest with yearly rebalancing +SDRB.opt.bt <- optimize.portfolio.rebalancing(R, SDRB.portf, + optimize_method="random", + rp=rp, + trace=TRUE, + rebalance_on="years", + training_period=100, + trailing_periods=60) + +# print method for optimize.portfolio.rebalancing objects +SDRB.opt.bt + +# summary method for optimize.portfolio.rebalancing objects +tmp_summary <- summary(SDRB.opt.bt) +names(tmp_summary) + +# print method for summary.optimize.portfolio.rebalancing objects +tmp_summary + +# Extractor functions for summary.optimize.portfolio.rebalancing objects +extractWeights(tmp_summary) +extractObjectiveMeasures(tmp_summary) + +# Extractor functions for optimize.portfolio.rebalancing objects +tmp_stats <- extractStats(SDRB.opt.bt) +head(tmp_stats[[1]]) +tmp_weights <- extractWeights(SDRB.opt.bt) +tmp_obj <- extractObjectiveMeasures(SDRB.opt.bt) + +# chart functions for optimize.portfolio.rebalancing +chart.Weights(SDRB.opt.bt) +chart.RiskBudget(SDRB.opt.bt, match.col="StdDev", risk.type="percent") + From noreply at r-forge.r-project.org Thu Feb 13 20:49:26 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 13 Feb 2014 20:49:26 +0100 (CET) Subject: [Returnanalytics-commits] r3308 - pkg/PerformanceAnalytics/R Message-ID: <20140213194926.21B5D186821@r-forge.r-project.org> Author: peter_carl Date: 2014-02-13 20:49:25 +0100 (Thu, 13 Feb 2014) New Revision: 3308 Modified: pkg/PerformanceAnalytics/R/chart.Histogram.R Log: - replaced 'sn' dependency with 'gamlss' for skew-t fit Modified: pkg/PerformanceAnalytics/R/chart.Histogram.R =================================================================== --- pkg/PerformanceAnalytics/R/chart.Histogram.R 2014-02-10 00:06:24 UTC (rev 3307) +++ pkg/PerformanceAnalytics/R/chart.Histogram.R 2014-02-13 19:49:25 UTC (rev 3308) @@ -225,11 +225,10 @@ probability = TRUE }, add.sst = { -# requires library(sn) - stopifnot("package:sn" %in% search() || require("sn",quietly=TRUE)) - - fit = st.mle(y=x) - fitted.sst = dst(s, location = fit$dp[[1]], scale = fit$dp[[2]], shape = fit$dp[[3]], df=fit$dp[[4]], log = FALSE) +# requires library(gamlss) + stopifnot("package:gamlss" %in% search() || require("gamlss",quietly=TRUE)) + fit = gamlss(coredata(y)~1, family="ST1", verbose=FALSE) + fitted.sst = dST1(s, mu = fitted(fit)[1], sigma = fitted(fit, "sigma")[1], nu = fitted(fit, "nu")[1], tau = fitted(fit, "tau")[1]) yrange=c(yrange,max(fitted.sst)) probability = TRUE }, @@ -297,6 +296,7 @@ # }, add.sst = { #requires package sn lines(s, fitted.sst, col = colorset[4], lwd=lwd) +# curve(fitted.sst, col=colorset[4], lwd=lwd, add=TRUE) }, add.rug = { rug(x, col = element.color) From noreply at r-forge.r-project.org Thu Feb 13 20:51:14 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 13 Feb 2014 20:51:14 +0100 (CET) Subject: [Returnanalytics-commits] r3309 - pkg/PerformanceAnalytics Message-ID: <20140213195114.82CAA18686C@r-forge.r-project.org> Author: peter_carl Date: 2014-02-13 20:51:14 +0100 (Thu, 13 Feb 2014) New Revision: 3309 Modified: pkg/PerformanceAnalytics/DESCRIPTION Log: - switched dependency from 'sn' to 'gamlss' Modified: pkg/PerformanceAnalytics/DESCRIPTION =================================================================== --- pkg/PerformanceAnalytics/DESCRIPTION 2014-02-13 19:49:25 UTC (rev 3308) +++ pkg/PerformanceAnalytics/DESCRIPTION 2014-02-13 19:51:14 UTC (rev 3309) @@ -23,7 +23,7 @@ MASS, tseries, quadprog, - sn, + gamlss, robustbase, quantreg, gplots, From noreply at r-forge.r-project.org Thu Feb 13 22:55:33 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 13 Feb 2014 22:55:33 +0100 (CET) Subject: [Returnanalytics-commits] r3310 - in pkg/PerformanceAnalytics: . R man Message-ID: <20140213215534.1DB87186B25@r-forge.r-project.org> Author: braverock Date: 2014-02-13 22:55:33 +0100 (Thu, 13 Feb 2014) New Revision: 3310 Added: pkg/PerformanceAnalytics/codeblock.txt pkg/PerformanceAnalytics/man/lpm.Rd Modified: pkg/PerformanceAnalytics/.Rbuildignore pkg/PerformanceAnalytics/NAMESPACE pkg/PerformanceAnalytics/R/legend.R pkg/PerformanceAnalytics/R/textplot.R pkg/PerformanceAnalytics/R/zzz.R pkg/PerformanceAnalytics/generatechangelog.sh pkg/PerformanceAnalytics/man/DownsideDeviation.Rd pkg/PerformanceAnalytics/man/MSquared.Rd Log: - update roxygen docs - update exports to create roxygen-generated NAMESPACE file Modified: pkg/PerformanceAnalytics/.Rbuildignore =================================================================== --- pkg/PerformanceAnalytics/.Rbuildignore 2014-02-13 19:51:14 UTC (rev 3309) +++ pkg/PerformanceAnalytics/.Rbuildignore 2014-02-13 21:55:33 UTC (rev 3310) @@ -1,3 +1,5 @@ sandbox generatechangelog.sh ChangeLog.1.0.0 +^.*\.Rproj$ +^\.Rproj\.user$ Modified: pkg/PerformanceAnalytics/NAMESPACE =================================================================== --- pkg/PerformanceAnalytics/NAMESPACE 2014-02-13 19:51:14 UTC (rev 3309) +++ pkg/PerformanceAnalytics/NAMESPACE 2014-02-13 21:55:33 UTC (rev 3310) @@ -1,460 +1,202 @@ -# NAMESPACE file for PerformanceAnalytics - -importFrom("utils", "packageDescription") -importFrom("stats", "sd") - -importFrom("zoo", "rollapply") - -# export all functions/variables that don't start with a . -# exportPattern("^[^\\.]") - - -export( - ActivePremium, - AdjustedSharpeRatio, - apply.fromstart, - apply.rolling, - AppraisalRatio, - AverageDrawdown, - AverageRecovery, - BernardoLedoitRatio, - BetaCoKurtosis, - BetaCoSkewness, - BetaCoVariance, - BurkeRatio, - CalculateReturns, - CalmarRatio, - CAPM.alpha, - CAPM.beta, - CAPM.beta.bear, - CAPM.beta.bull, - CAPM.CML, - CAPM.CML.slope, - CAPM.dynamic, - CAPM.epsilon, - CAPM.jensenAlpha, - CAPM.RiskPremium, - CAPM.SML.slope, - CDD, - checkData, - clean.boudt, - CoKurtosis, -# CoKurtosisMatrix, #export after co-moments paper is done - CoSkewness, -# CoSkewnessMatrix, #export after co-moments paper is done - CoVariance, - DownsideDeviation, - DownsideFrequency, - DownsidePotential, - DRatio, - Drawdowns, - DrawdownDeviation, - ES, - ETL, - CVaR, - DrawdownPeak, - findDrawdowns, - FamaBeta, - Frequency, - InformationRatio, - Kappa, - KellyRatio, - kurtosis, - M2Sortino, - maxDrawdown, - MarketTiming, - MartinRatio, - MeanAbsoluteDeviation, - mean.geometric, - mean.LCL, - mean.stderr, - mean.UCL, - Modigliani, - MSquared, - MSquaredExcess, - NetSelectivity, - Omega, - OmegaExcessReturn, - OmegaSharpeRatio, -# pfolioReturn, - PainIndex, - PainRatio, - ProspectRatio, - Return.annualized, - Return.annualized.excess, - Return.calculate, - Return.centered, - Return.clean, - Return.cumulative, - Return.excess, - Return.Geltner, - Return.portfolio, - Return.rebalancing, - Return.read, - Return.relative, - sd.annualized, - sd.multiperiod, - Selectivity, - SemiDeviation, - SemiVariance, - SharpeRatio, - SharpeRatio.annualized, - SharpeRatio.modified, - skewness, - SkewnessKurtosisRatio, - SmoothingIndex, - sortDrawdowns, - SortinoRatio, - SpecificRisk, - StdDev, - StdDev.annualized, - SterlingRatio, - SystematicRisk, -# style.fit, -# style.QPfit, - TimingRatio, - TotalRisk, - TrackingError, - TreynorRatio, - UpDownRatios, - UPR, - UpsideFrequency, - UpsidePotentialRatio, - UpsideRisk, - VaR, - VolatilitySkewness -) - -## Tables -export( - table.AnnualizedReturns, - table.Arbitrary, - table.Autocorrelation, - table.CalendarReturns, - table.CAPM, - table.SFM, - table.CaptureRatios, - table.Correlation, - table.Distributions, - table.DownsideRisk, - table.DownsideRiskRatio, - table.Drawdowns, - table.DrawdownsRatio, - table.HigherMoments, - table.InformationRatio, - table.Returns, - table.SpecificRisk, - table.Stats, - table.TrailingPeriods, - table.TrailingPeriodsRel, - table.UpDownRatios, - table.Variability -) - -## Charts -export( - chart.ACF, - chart.ACFplus, - chart.Bar, - charts.Bar, - chart.BarVaR, - charts.BarVaR, - chart.Boxplot, - chart.CaptureRatios, - chart.Correlation, -# chart.Correlation.color, - chart.CumReturns, - chart.Drawdown, - chart.ECDF, - chart.Events, - chart.Histogram, - chart.QQPlot, - chart.Regression, - chart.RelativePerformance, - chart.RiskReturnScatter, - chart.RollingCorrelation, - chart.RollingMean, - chart.RollingPerformance, - chart.RollingRegression, - chart.RollingQuantileRegression, -# chart.RollingStyle, - chart.Scatter, - chart.SnailTrail, - charts.PerformanceSummary, - charts.RollingPerformance, - charts.RollingRegression, - chart.StackedBar, -# chart.Style, - chart.TimeSeries, - chart.VaRSensitivity, - textplot -) - -export( - allsymbols, - bluefocus, - bluemono, - bond.dates, - bond.labels, - closedsymbols, - cycles.dates, - dark6equal, - dark8equal, - equity.dates, - equity.labels, - fillsymbols, - greenfocus, - greenmono, - grey6mono, - grey8mono, - legend, - linesymbols, - macro.dates, - macro.labels, - opensymbols, - rainbow10equal, - rainbow12equal, - rainbow6equal, - rainbow8equal, - redfocus, - redmono, - rich10equal, - rich12equal, - rich6equal, - rich8equal, - risk.dates, - risk.labels, - set6equal, - set8equal, - tim10equal, - tim12equal, - tim6equal, - tim8equal -) - -S3method(textplot, default) -S3method(textplot, character) -S3method(textplot, data.frame) -S3method(textplot, matrix) - -# # Export These -# ActivePremium -# apply.fromstart -# apply.rolling -# BetaCoKurtosis -# BetaCoSkewness -# BetaCoVariance -# CalculateReturns -# CalmarRatio -# CAPM.alpha -# CAPM.beta -# CAPM.beta.bear -# CAPM.beta.bull -# CAPM.CML -# CAPM.CML.slope -# CAPM.RiskPremium -# CAPM.SML.slope -# chart.ACF -# chart.ACFplus -# chart.Bar -# chart.BarVaR -# chart.Boxplot -# chart.CaptureRatios -# chart.Correlation -# chart.Correlation.color -# chart.CumReturns -# chart.Drawdown -# chart.ECDF -# chart.Histogram -# chart.QQPlot -# chart.Regression -# chart.RelativePerformance -# chart.RiskReturnScatter -# chart.RollingCorrelation -# chart.RollingMean -# chart.RollingPerformance -# chart.RollingRegression -# chart.RollingStyle -# chart.Scatter -# chart.SnailTrail -# charts.PerformanceSummary -# charts.RollingPerformance -# charts.RollingRegression -# chart.StackedBar -# chart.Style -# chart.TimeSeries -# chart.VaRSensitivity -# checkData -# clean.boudt -# CoKurtosis -# CoKurtosisMatrix -# CoSkewness -# CoSkewnessMatrix -# CoVariance -# DownsideDeviation -# Drawdowns -# ES -# findDrawdowns -# InformationRatio -# KellyRatio -# kurtosis -# maxDrawdown -# mean.geometric -# mean.LCL -# mean.stderr -# mean.UCL -# modifiedVaR -# modSharpe -# multivariate_mean -# Omega -# pfolioReturn -# Return.annualized -# Return.calculate -# Return.centered -# Return.clean -# Return.cumulative -# Return.excess -# Return.Geltner -# Return.portfolio -# Return.portfolio.multiweight -# Return.read -# Return.relative -# sd.annualized -# sd.multiperiod -# SemiDeviation -# SemiVariance -# SharpeRatio -# SharpeRatio.annualized -# SharpeRatio.modified -# skewness -# SmoothingIndex -# sortDrawdowns -# SortinoRatio -# SterlingRatio -# style.fit -# style.QPfit -# table.AnnualizedReturns -# table.Arbitrary -# table.Autocorrelation -# table.CalendarReturns -# table.CAPM -# table.CaptureRatios -# table.Correlation -# table.DownsideRisk -# table.Drawdowns -# table.HigherMoments -# table.MonthlyReturns -# table.Returns -# table.UpDownRatios -# textplot -# TimingRatio -# TrackingError -# TreynorRatio -# UpDownRatios -# UPR -# UpsidePotentialRatio -# VaR - -# # graphics stuff to export -# allsymbols -# bluefocus -# bluemono -# bond.dates -# bond.labels -# closedsymbols -# cycles.dates -# dark6equal -# dark8equal -# equity.dates -# equity.labels -# fillsymbols -# greenfocus -# greenmono -# grey6mono -# grey8mono -# legend -# linesymbols -# macro.dates -# macro.labels -# opensymbols -# rainbow10equal -# rainbow12equal -# rainbow6equal -# rainbow8equal -# redfocus -# redmono -# rich10equal -# rich12equal -# rich6equal -# rich8equal -# risk.dates -# risk.labels -# set6equal -# set8equal -# tim10equal -# tim12equal -# tim6equal -# tim8equal - -# # internal/obsolete functions, do not export -# centeredcomoment -# centeredmoment -# checkDataMatrix -# checkDataVector -# checkDataZoo -# derIpower -# derportm2 -# derportm3 -# derportm4 -# download.RiskFree -# download.SP500PriceReturns -# ES.CornishFisher -# ES.CornishFisher.portfolio -# ES.Gaussian -# ES.Gaussian.portfolio -# ES.historical.portfolio -# GES.MM -# GVaR.MM -# Ipower -# kernel -# kurtosis.MM -# mES.MM -# modifiedVaR -# multivariate_mean -# mVaR.MM -# M3.MM -# M4.MM -# portm2 -# portm3 -# portm4 -# Portmean -# Portsd -# precision -# pvalJB -# operES.CornishFisher -# operES.CornishFisher.portfolio -# skewness.MM -# SR.GES.MM -# SR.GVaR.MM -# SR.mES.MM -# SR.mVaR.MM -# SR.StdDev.MM -# statsTable -# std -# StdDev.annualized -# StdDev.MM -# textplot.character -# textplot.data.frame -# textplot.default -# textplot.matrix -# timing.ratio -# VaR.Beyond -# VaR.CornishFisher -# VaR.CornishFisher.portfolio -# VaR.Gaussian -# VaR.Gaussian.portfolio -# VaR.historical.portfolio -# VaR.kernel.portfolio -# VaR.Marginal -# VaR.mean -# VaR.traditional +S3method(mean,LCL) +S3method(mean,UCL) +S3method(mean,geometric) +S3method(mean,stderr) +S3method(textplot,character) +S3method(textplot,data.frame) +S3method(textplot,default) +S3method(textplot,matrix) +export(ActiveReturn) +export(AdjustedSharpeRatio) +export(AppraisalRatio) +export(AverageDrawdown) +export(AverageRecovery) +export(BernardoLedoitRatio) +export(BetaCoKurtosis) +export(BetaCoSkewness) +export(BetaCoVariance) +export(BurkeRatio) +export(CAPM.CML) +export(CAPM.CML.slope) +export(CAPM.RiskPremium) +export(CAPM.SML.slope) +export(CAPM.alpha) +export(CAPM.beta) +export(CAPM.beta.bear) +export(CAPM.beta.bull) +export(CAPM.dynamic) +export(CAPM.epsilon) +export(CAPM.jensenAlpha) +export(CDD) +export(CalculateReturns) +export(CalmarRatio) +export(CoKurtosis) +export(CoSkewness) +export(CoVariance) +export(DRatio) +export(DownsideDeviation) +export(DownsideFrequency) +export(DrawdownDeviation) +export(DrawdownPeak) +export(ETL) +export(FamaBeta) +export(Frequency) +export(InformationRatio) +export(Kappa) +export(KellyRatio) +export(M2Sortino) +export(MSquared) +export(MSquaredExcess) +export(MarketTiming) +export(MartinRatio) +export(MeanAbsoluteDeviation) +export(Modigliani) +export(NetSelectivity) +export(Omega) +export(OmegaExcessReturn) +export(OmegaSharpeRatio) +export(PainIndex) +export(PainRatio) +export(ProspectRatio) +export(Return.Geltner) +export(Return.annualized) +export(Return.annualized.excess) +export(Return.calculate) +export(Return.centered) +export(Return.clean) +export(Return.cumulative) +export(Return.excess) +export(Return.portfolio) +export(Return.read) +export(Return.rebalancing) +export(Return.relative) +export(Selectivity) +export(SemiDeviation) +export(SemiVariance) +export(SharpeRatio) +export(SharpeRatio.annualized) +export(SharpeRatio.modified) +export(SkewnessKurtosisRatio) +export(SmoothingIndex) +export(SortinoRatio) +export(SpecificRisk) +export(StdDev) +export(StdDev.annualized) +export(SterlingRatio) +export(SystematicRisk) +export(TimingRatio) +export(TotalRisk) +export(TrackingError) +export(TreynorRatio) +export(UlcerIndex) +export(UpDownRatios) +export(UpsideFrequency) +export(UpsidePotentialRatio) +export(UpsideRisk) +export(VaR) +export(VolatilitySkewness) +export(allsymbols) +export(apply.fromstart) +export(apply.rolling) +export(bluefocus) +export(bluemono) +export(bond.dates) +export(bond.labels) +export(centeredcomoment) +export(centeredmoment) +export(chart.ACF) +export(chart.ACFplus) +export(chart.Bar) +export(chart.BarVaR) +export(chart.Boxplot) +export(chart.CaptureRatios) +export(chart.Correlation) +export(chart.CumReturns) +export(chart.Drawdown) +export(chart.ECDF) +export(chart.Events) +export(chart.Histogram) +export(chart.QQPlot) +export(chart.Regression) +export(chart.RelativePerformance) +export(chart.RiskReturnScatter) +export(chart.RollingCorrelation) +export(chart.RollingMean) +export(chart.RollingPerformance) +export(chart.RollingQuantileRegression) +export(chart.RollingRegression) +export(chart.Scatter) +export(chart.SnailTrail) +export(chart.StackedBar) +export(chart.TimeSeries) +export(chart.VaRSensitivity) +export(charts.Bar) +export(charts.BarVaR) +export(charts.PerformanceSummary) +export(charts.RollingPerformance) +export(charts.RollingRegression) +export(charts.TimeSeries) +export(checkData) +export(clean.boudt) +export(closedsymbols) +export(cycles.dates) +export(dark6equal) +export(dark8equal) +export(equity.dates) +export(equity.labels) +export(fillsymbols) +export(findDrawdowns) +export(greenfocus) +export(greenmono) +export(grey6mono) +export(grey8mono) +export(kurtosis) +export(legend) +export(linesymbols) +export(lpm) +export(macro.dates) +export(macro.labels) +export(maxDrawdown) +export(opensymbols) +export(rainbow10equal) +export(rainbow12equal) +export(rainbow6equal) +export(rainbow8equal) +export(redfocus) +export(redmono) +export(rich10equal) +export(rich12equal) +export(rich6equal) +export(rich8equal) +export(risk.dates) +export(risk.labels) +export(set6equal) +export(set8equal) +export(skewness) +export(sortDrawdowns) +export(table.AnnualizedReturns) +export(table.Arbitrary) +export(table.Autocorrelation) +export(table.CalendarReturns) +export(table.CaptureRatios) +export(table.Correlation) +export(table.Distributions) +export(table.DownsideRisk) +export(table.DownsideRiskRatio) +export(table.Drawdowns) +export(table.DrawdownsRatio) +export(table.HigherMoments) +export(table.InformationRatio) +export(table.SFM) +export(table.SpecificRisk) +export(table.Stats) +export(table.TrailingPeriods) +export(table.Variability) +export(textplot) +export(tim10equal) +export(tim12equal) +export(tim6equal) +export(tim8equal) +importFrom(stats,sd) +importFrom(utils,packageDescription) +importFrom(zoo,rollapply) Modified: pkg/PerformanceAnalytics/R/legend.R =================================================================== --- pkg/PerformanceAnalytics/R/legend.R 2014-02-13 19:51:14 UTC (rev 3309) +++ pkg/PerformanceAnalytics/R/legend.R 2014-02-13 21:55:33 UTC (rev 3310) @@ -81,6 +81,11 @@ #' @seealso \code{\link[graphics]{legend}} #' @keywords internal #' @export +#' @export allsymbols bluefocus bluemono bond.dates bond.labels closedsymbols cycles.dates +#' @export dark6equal dark8equal equity.dates equity.labels fillsymbols greenfocus greenmono grey6mono +#' @export grey8mono legend linesymbols macro.dates macro.labels opensymbols rainbow10equal +#' @export rainbow12equal rainbow6equal rainbow8equal redfocus redmono rich10equal rich12equal rich6equal +#' @export rich8equal risk.dates risk.labels set6equal set8equal tim10equal tim12equal tim6equal tim8equal legend <- function (x, y = NULL, legend, fill = NULL, col = par("col"), lty, lwd, pch, angle = 45, density = NULL, bty = "o", bg = par("bg"), Modified: pkg/PerformanceAnalytics/R/textplot.R =================================================================== --- pkg/PerformanceAnalytics/R/textplot.R 2014-02-13 19:51:14 UTC (rev 3309) +++ pkg/PerformanceAnalytics/R/textplot.R 2014-02-13 21:55:33 UTC (rev 3310) @@ -92,7 +92,11 @@ #' #' # title(main="Calendar Returns") #' -#' +#' @S3method textplot default +#' @S3method textplot character +#' @S3method textplot data.frame +#' @S3method textplot matrix +#' #' @export textplot <- function(object, halign="center", valign="center", cex, max.cex = 1, cmar=2, rmar=0.5, Modified: pkg/PerformanceAnalytics/R/zzz.R =================================================================== --- pkg/PerformanceAnalytics/R/zzz.R 2014-02-13 19:51:14 UTC (rev 3309) +++ pkg/PerformanceAnalytics/R/zzz.R 2014-02-13 21:55:33 UTC (rev 3310) @@ -16,6 +16,12 @@ odd <- function (x) x%%2==1 sd.xts <- xts:::sd.xts + +#' @importFrom utils packageDescription +#' @importFrom stats sd +#' @importFrom zoo rollapply +NULL + ############################################################################### # R (http://r-project.org/) Econometrics for Performance and Risk Analysis # Added: pkg/PerformanceAnalytics/codeblock.txt =================================================================== --- pkg/PerformanceAnalytics/codeblock.txt (rev 0) +++ pkg/PerformanceAnalytics/codeblock.txt 2014-02-13 21:55:33 UTC (rev 3310) @@ -0,0 +1,13 @@ + + +############################################################################### +# R (http://r-project.org/) Econometrics for Performance and Risk Analysis +# +# Copyright (c) 2004-2014 Peter Carl and Brian G. Peterson +# +# This R package is distributed under the terms of the GNU Public License (GPL) +# for full details see the file COPYING +# +# $Id$ +# +############################################################################### Property changes on: pkg/PerformanceAnalytics/codeblock.txt ___________________________________________________________________ Added: svn:keywords + Date Author Revision Id Modified: pkg/PerformanceAnalytics/generatechangelog.sh =================================================================== --- pkg/PerformanceAnalytics/generatechangelog.sh 2014-02-13 19:51:14 UTC (rev 3309) +++ pkg/PerformanceAnalytics/generatechangelog.sh 2014-02-13 21:55:33 UTC (rev 3310) @@ -3,4 +3,4 @@ #cvs2cl -T -P -S --no-wrap svn2cl --group-by-day -a svn2cl --group-by-day -a -cat ChangeLog.1.0.0 >> ChangeLog +#cat ChangeLog.1.0.0 >> ChangeLog Modified: pkg/PerformanceAnalytics/man/DownsideDeviation.Rd =================================================================== --- pkg/PerformanceAnalytics/man/DownsideDeviation.Rd 2014-02-13 19:51:14 UTC (rev 3309) +++ pkg/PerformanceAnalytics/man/DownsideDeviation.Rd 2014-02-13 21:55:33 UTC (rev 3310) @@ -106,9 +106,9 @@ #with data used in Bacon 2008 data(portfolio_bacon) -MAR = 0.5 -DownsideDeviation(portfolio_bacon[,1], MAR) #expected 0.493 -DownsidePotential(portfolio_bacon[,1], MAR) #expected 0.491 +MAR = 0.005 +DownsideDeviation(portfolio_bacon[,1], MAR) #expected 0.0255 +DownsidePotential(portfolio_bacon[,1], MAR) #expected 0.0137 #with data of managers Modified: pkg/PerformanceAnalytics/man/MSquared.Rd =================================================================== --- pkg/PerformanceAnalytics/man/MSquared.Rd 2014-02-13 19:51:14 UTC (rev 3309) +++ pkg/PerformanceAnalytics/man/MSquared.Rd 2014-02-13 21:55:33 UTC (rev 3310) @@ -32,7 +32,7 @@ } \examples{ data(portfolio_bacon) -print(MSquared(portfolio_bacon[,1], portfolio_bacon[,2])) #expected 0.1068 +print(MSquared(portfolio_bacon[,1], portfolio_bacon[,2])) #expected 0.10062 data(managers) print(MSquared(managers['1996',1], managers['1996',8])) Added: pkg/PerformanceAnalytics/man/lpm.Rd =================================================================== --- pkg/PerformanceAnalytics/man/lpm.Rd (rev 0) +++ pkg/PerformanceAnalytics/man/lpm.Rd 2014-02-13 21:55:33 UTC (rev 3310) @@ -0,0 +1,29 @@ +\name{lpm} +\alias{lpm} +\title{calculate the lower partial moment of a time series} +\usage{ + lpm(R, n, threshold, about_mean = FALSE) +} +\arguments{ + \item{R}{xts data} + + \item{n}{the n-th moment to return} + + \item{threshold}{threshold can be the mean or any point + as desired} + + \item{about_mean}{TRUE/FALSE calculate LPM about the mean + under the threshold or use the threshold to calculate the + LPM around (if FALSE)} +} +\description{ + Code to calculate the Lower Partion Moments around the + mean or a specified threshold from Huffman S,P & Moll + C.R. 2011 "The impact of Asymmetry on Expected Stock + Returns: An Investigation of Alternative Risk Measures" + Algorithmic Finance 1 (2011) 79-93 +} +\author{ + Kyle Balkissoon /email{kylebalkissoon +} + From noreply at r-forge.r-project.org Thu Feb 13 23:19:11 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 13 Feb 2014 23:19:11 +0100 (CET) Subject: [Returnanalytics-commits] r3311 - in pkg/PerformanceAnalytics: . R Message-ID: <20140213221911.C03E4186ED3@r-forge.r-project.org> Author: braverock Date: 2014-02-13 23:19:11 +0100 (Thu, 13 Feb 2014) New Revision: 3311 Modified: pkg/PerformanceAnalytics/NAMESPACE pkg/PerformanceAnalytics/R/ES.R pkg/PerformanceAnalytics/R/table.CAPM.R Log: - more roxygen NAMESPACE changes Modified: pkg/PerformanceAnalytics/NAMESPACE =================================================================== --- pkg/PerformanceAnalytics/NAMESPACE 2014-02-13 21:55:33 UTC (rev 3310) +++ pkg/PerformanceAnalytics/NAMESPACE 2014-02-13 22:19:11 UTC (rev 3311) @@ -28,6 +28,7 @@ export(CAPM.epsilon) export(CAPM.jensenAlpha) export(CDD) +export(CVaR) export(CalculateReturns) export(CalmarRatio) export(CoKurtosis) @@ -38,6 +39,7 @@ export(DownsideFrequency) export(DrawdownDeviation) export(DrawdownPeak) +export(ES) export(ETL) export(FamaBeta) export(Frequency) @@ -177,6 +179,7 @@ export(table.AnnualizedReturns) export(table.Arbitrary) export(table.Autocorrelation) +export(table.CAPM) export(table.CalendarReturns) export(table.CaptureRatios) export(table.Correlation) Modified: pkg/PerformanceAnalytics/R/ES.R =================================================================== --- pkg/PerformanceAnalytics/R/ES.R 2014-02-13 21:55:33 UTC (rev 3310) +++ pkg/PerformanceAnalytics/R/ES.R 2014-02-13 22:19:11 UTC (rev 3311) @@ -114,7 +114,7 @@ #' #' # add Component ES for the equal weighted portfolio #' ES(edhec, clean="boudt", portfolio_method="component") -#' +#' @export ETL CVaR ES ETL <- CVaR <- ES <- function (R=NULL , p=0.95, ..., method=c("modified","gaussian","historical"), clean=c("none","boudt", "geltner"), Modified: pkg/PerformanceAnalytics/R/table.CAPM.R =================================================================== --- pkg/PerformanceAnalytics/R/table.CAPM.R 2014-02-13 21:55:33 UTC (rev 3310) +++ pkg/PerformanceAnalytics/R/table.CAPM.R 2014-02-13 22:19:11 UTC (rev 3311) @@ -31,7 +31,7 @@ #' @aliases #' table.CAPM #' table.SFM -#' @export +#' @export table.SFM table.CAPM table.SFM <- table.CAPM <- function (Ra, Rb, scale = NA, Rf = 0, digits = 4) {# @author Peter Carl From noreply at r-forge.r-project.org Fri Feb 14 04:04:37 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 14 Feb 2014 04:04:37 +0100 (CET) Subject: [Returnanalytics-commits] r3312 - pkg/PerformanceAnalytics/R Message-ID: <20140214030437.E837318700B@r-forge.r-project.org> Author: peter_carl Date: 2014-02-14 04:04:37 +0100 (Fri, 14 Feb 2014) New Revision: 3312 Modified: pkg/PerformanceAnalytics/R/legend.R Log: - added exports for tol color schemes Modified: pkg/PerformanceAnalytics/R/legend.R =================================================================== --- pkg/PerformanceAnalytics/R/legend.R 2014-02-13 22:19:11 UTC (rev 3311) +++ pkg/PerformanceAnalytics/R/legend.R 2014-02-14 03:04:37 UTC (rev 3312) @@ -86,6 +86,8 @@ #' @export grey8mono legend linesymbols macro.dates macro.labels opensymbols rainbow10equal #' @export rainbow12equal rainbow6equal rainbow8equal redfocus redmono rich10equal rich12equal rich6equal #' @export rich8equal risk.dates risk.labels set6equal set8equal tim10equal tim12equal tim6equal tim8equal +#' @export tol1qualitative tol2qualitative tol3qualitative tol4qualitative tol5qualitative tol6qualitative tol7qualitative tol8qualitative tol9qualitative tol10qualitative tol11qualitative tol12qualitative +#' @export tol14rainbow tol15rainbow tol18rainbow tol21rainbow legend <- function (x, y = NULL, legend, fill = NULL, col = par("col"), lty, lwd, pch, angle = 45, density = NULL, bty = "o", bg = par("bg"), @@ -438,6 +440,31 @@ grey6mono = c("#242424", "#494949", "#6D6D6D", "#929292", "#B6B6B6", "#DBDBDB") + # QUALITATIVE + # by Paul Tol, http://www.sron.nl/~pault/colourschemes.pdf + tol1qualitative=c("#4477AA") + tol2qualitative=c("#4477AA", "#CC6677") + tol3qualitative=c("#4477AA", "#DDCC77", "#CC6677") + tol4qualitative=c("#4477AA", "#117733", "#DDCC77", "#CC6677") + tol5qualitative=c("#332288", "#88CCEE", "#117733", "#DDCC77", "#CC6677") + tol6qualitative=c("#332288", "#88CCEE", "#117733", "#DDCC77", "#CC6677","#AA4499") + tol7qualitative=c("#332288", "#88CCEE", "#44AA99", "#117733", "#DDCC77", "#CC6677","#AA4499") + tol8qualitative=c("#332288", "#88CCEE", "#44AA99", "#117733", "#999933", "#DDCC77", "#CC6677","#AA4499") + tol9qualitative=c("#332288", "#88CCEE", "#44AA99", "#117733", "#999933", "#DDCC77", "#CC6677", "#882255", "#AA4499") + tol10qualitative=c("#332288", "#88CCEE", "#44AA99", "#117733", "#999933", "#DDCC77", "#661100", "#CC6677", "#882255", "#AA4499") + tol11qualitative=c("#332288", "#6699CC", "#88CCEE", "#44AA99", "#117733", "#999933", "#DDCC77", "#661100", "#CC6677", "#882255", "#AA4499") + tol12qualitative=c("#332288", "#6699CC", "#88CCEE", "#44AA99", "#117733", "#999933", "#DDCC77", "#661100", "#CC6677", "#AA4466", "#882255", "#AA4499") + + # A recent update to his technical paper adds a new banded rainbow scheme, several with a large number of steps. He notes that when you're using them, you're better off picking a scheme that matches the number of colors needed, rather than using only a few colors from a larger scheme. + + tol14rainbow=c("#882E72", "#B178A6", "#D6C1DE", "#1965B0", "#5289C7", "#7BAFDE", "#4EB265", "#90C987", "#CAE0AB", "#F7EE55", "#F6C141", "#F1932D", "#E8601C", "#DC050C") + + tol15rainbow=c("#114477", "#4477AA", "#77AADD", "#117755", "#44AA88", "#99CCBB", "#777711", "#AAAA44", "#DDDD77", "#771111", "#AA4444", "#DD7777", "#771144", "#AA4477", "#DD77AA") + + tol18rainbow=c("#771155", "#AA4488", "#CC99BB", "#114477", "#4477AA", "#77AADD", "#117777", "#44AAAA", "#77CCCC", "#777711", "#AAAA44", "#DDDD77", "#774411", "#AA7744", "#DDAA77", "#771122", "#AA4455", "#DD7788") + + tol21rainbow= c("#771155", "#AA4488", "#CC99BB", "#114477", "#4477AA", "#77AADD", "#117777", "#44AAAA", "#77CCCC", "#117744", "#44AA77", "#88CCAA", "#777711", "#AAAA44", "#DDDD77", "#774411", "#AA7744", "#DDAA77", "#771122", "#AA4455", "#DD7788") + # ------------------------------------------------------------------------------ # These are sets of data symbols for use as either pch or symbolset From noreply at r-forge.r-project.org Mon Feb 17 03:11:55 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 17 Feb 2014 03:11:55 +0100 (CET) Subject: [Returnanalytics-commits] r3313 - in pkg/PortfolioAnalytics: . R demo man Message-ID: <20140217021155.474BD183E6E@r-forge.r-project.org> Author: rossbennett34 Date: 2014-02-17 03:11:49 +0100 (Mon, 17 Feb 2014) New Revision: 3313 Added: pkg/PortfolioAnalytics/R/chart.concentration.R pkg/PortfolioAnalytics/demo/chart_concentration.R pkg/PortfolioAnalytics/man/chart.Concentration.Rd Modified: pkg/PortfolioAnalytics/DESCRIPTION pkg/PortfolioAnalytics/NAMESPACE pkg/PortfolioAnalytics/demo/00Index Log: Adding function to chart concentration based on Peter's symposium slides along with a demo Modified: pkg/PortfolioAnalytics/DESCRIPTION =================================================================== --- pkg/PortfolioAnalytics/DESCRIPTION 2014-02-14 03:04:37 UTC (rev 3312) +++ pkg/PortfolioAnalytics/DESCRIPTION 2014-02-17 02:11:49 UTC (rev 3313) @@ -64,3 +64,4 @@ 'equal.weight.R' 'inverse.volatility.weight.R' 'utils.R' + 'chart.concentration.R' Modified: pkg/PortfolioAnalytics/NAMESPACE =================================================================== --- pkg/PortfolioAnalytics/NAMESPACE 2014-02-14 03:04:37 UTC (rev 3312) +++ pkg/PortfolioAnalytics/NAMESPACE 2014-02-17 02:11:49 UTC (rev 3313) @@ -3,6 +3,7 @@ export(applyFUN) export(box_constraint) export(CCCgarch.MM) +export(chart.Concentration) export(chart.EfficientFrontier) export(chart.EfficientFrontierOverlay) export(chart.GroupWeights) Added: pkg/PortfolioAnalytics/R/chart.concentration.R =================================================================== --- pkg/PortfolioAnalytics/R/chart.concentration.R (rev 0) +++ pkg/PortfolioAnalytics/R/chart.concentration.R 2014-02-17 02:11:49 UTC (rev 3313) @@ -0,0 +1,181 @@ + +# conc.type = weight or pct_contrib for risk budget optimization + +#' Classic risk reward scatter and concentration +#' +#' This function charts the \code{optimize.portfolio} object in risk-return space +#' and the degree of concentration based on the weights or percentage component +#' contribution to risk. +#' +#' @param object optimal portfolio created by \code{\link{optimize.portfolio}}. +#' @param \dots any other passthru parameters. +#' @param return.col string matching the objective of a 'return' objective, on vertical axis. +#' @param risk.col string matching the objective of a 'risk' objective, on horizontal axis. +#' @param chart.assets TRUE/FALSE. Includes a risk reward scatter of the assets in the chart. +#' @param conc.type concentration type can be based on the concentration of weights +#' or concentration of percentage component contribution to risk (only works with risk +#' budget objective for the optimization). +#' @param col color palette or vector of colors to use. +#' @param element.color color for the border and axes. +#' @param cex.axis The magnification to be used for axis annotation relative to the current setting of \code{cex}. +#' @param xlim set the x-axis limit, same as in \code{\link{plot}}. +#' @param ylim set the y-axis limit, same as in \code{\link{plot}}. +#' @seealso \code{\link{optimize.portfolio}} +#' @author Peter Carl and Ross Bennett +#' @export +chart.Concentration <- function(object, + ..., + return.col='mean', + risk.col='ES', + chart.assets=FALSE, + conc.type=c("weights", "pct_contrib"), + col=heat.colors(20), + element.color = "darkgray", + cex.axis=0.8, + xlim=NULL, ylim=NULL){ + # check the object + if(!inherits(object, "optimize.portfolio")){ + stop("object must be of class 'optimize.portfolio'") + } + + # extract the stats + xtract <- try(extractStats(object), silent=TRUE) + if(inherits(xtract, "try-error")) { + message(xtract) + return(NULL) + } + + # get the concentration type + # We can either chart the concentration of the weights or the concentration + # of the percentage contribution to risk for risk budget optimizations + conc.type <- match.arg(conc.type) + + columnnames <- colnames(xtract) + + # Get the return and risk columns from xtract + return.column <- pmatch(return.col, columnnames) + if(is.na(return.column)) { + return.col <- paste(return.col, return.col, sep='.') + return.column <- pmatch(return.col, columnnames) + } + risk.column <- pmatch(risk.col, columnnames) + if(is.na(risk.column)) { + risk.col <- paste(risk.col, risk.col, sep='.') + risk.column <- pmatch(risk.col, columnnames) + } + + # If the user has passed in return.col or risk.col that does not match extractStats output + # This will give the flexibility of passing in return or risk metrics that are not + # objective measures in the optimization. This may cause issues with the "neighbors" + # functionality since that is based on the "out" column + if(is.na(return.column) | is.na(risk.column)){ + return.col <- gsub("\\..*", "", return.col) + risk.col <- gsub("\\..*", "", risk.col) + warning(return.col,' or ', risk.col, ' do not match extractStats output of $objective_measures slot') + # Get the matrix of weights for applyFUN + wts_index <- grep("w.", columnnames) + wts <- xtract[, wts_index] + if(is.na(return.column)){ + tmpret <- applyFUN(R=R, weights=wts, FUN=return.col) + xtract <- cbind(tmpret, xtract) + colnames(xtract)[which(colnames(xtract) == "tmpret")] <- return.col + } + if(is.na(risk.column)){ + tmprisk <- applyFUN(R=R, weights=wts, FUN=risk.col) + xtract <- cbind(tmprisk, xtract) + colnames(xtract)[which(colnames(xtract) == "tmprisk")] <- risk.col + } + columnnames = colnames(xtract) + return.column = pmatch(return.col,columnnames) + if(is.na(return.column)) { + return.col = paste(return.col,return.col,sep='.') + return.column = pmatch(return.col,columnnames) + } + risk.column = pmatch(risk.col,columnnames) + if(is.na(risk.column)) { + risk.col = paste(risk.col,risk.col,sep='.') + risk.column = pmatch(risk.col,columnnames) + } + } + + if(chart.assets){ + # Get the arguments from the optimize.portfolio$portfolio object + # to calculate the risk and return metrics for the scatter plot. + # (e.g. arguments=list(p=0.925, clean="boudt") + arguments <- NULL # maybe an option to let the user pass in an arguments list? + if(is.null(arguments)){ + tmp.args <- unlist(lapply(object$portfolio$objectives, function(x) x$arguments), recursive=FALSE) + tmp.args <- tmp.args[!duplicated(names(tmp.args))] + if(!is.null(tmp.args$portfolio_method)) tmp.args$portfolio_method <- "single" + arguments <- tmp.args + } + # Include risk reward scatter of asset returns + asset_ret <- scatterFUN(R=R, FUN=return.col, arguments) + asset_risk <- scatterFUN(R=R, FUN=risk.col, arguments) + xlim <- range(c(xtract[,risk.column], asset_risk)) + ylim <- range(c(xtract[,return.column], asset_ret)) + } else { + asset_ret <- NULL + asset_risk <- NULL + } + + if(conc.type == "weights"){ + idx <- grep("w.", colnames(xtract)) + if(length(idx) == 0) stop("weights not detected in output of extractStats") + tmp.x <- xtract[, idx] + } else if(conc.type == "pct_contrib"){ + idx <- grep("pct_contrib", colnames(xtract)) + if(length(idx) == 0) stop("pct_contrib not detected in output of extractStats") + tmp.x <- xtract[, idx] + } + # need a check to make sure that tmp.x is valid + + # # Use HHI to compute the concentration of the pct_contrib_MES or concentration of weights + x.hhi <- apply(tmp.x, MARGIN=1, FUN="HHI") + # normalized HHI between 0 and 1 + y <- (x.hhi - min(x.hhi)) / (max(x.hhi) - min(x.hhi)) + + op <- par(no.readonly=TRUE) + layout(matrix(c(1,2)),height=c(4,1.25),width=1) + par(mar=c(5,4,1,2)+.1, cex=1) # c(bottom, left, top, right) + + # plot the asset in risk-return space ordered based on degree of concentration + plot(xtract[order(y, decreasing=TRUE), risk.column], xtract[order(y, decreasing=TRUE), return.column], xlab=risk.col, ylab=return.col, col=col, axes=FALSE, xlim=xlim, ylim=ylim, ...) + + # plot the risk-reward scatter of the assets + if(chart.assets){ + points(x=asset_risk, y=asset_ret) + text(x=asset_risk, y=asset_ret, labels=colnames(R), pos=4, cex=0.8) + } + + axis(1, cex.axis = cex.axis, col = element.color) + axis(2, cex.axis = cex.axis, col = element.color) + box(col = element.color) + + # Now plot the portfolio concentration part + # Add legend to bottom panel + par(mar=c(5,5.5,1,3)+.1, cex=0.7) + x <- x.hhi + scale01 <- function(x, low = min(x), high = max(x)) { + return((x - low) / (high - low)) + } + + breaks <- seq(min(x.hhi, na.rm=TRUE), max(x.hhi, na.rm=TRUE), length=(length(col)+1)) + min.raw <- min(x, na.rm = TRUE) + max.raw <- max(x, na.rm = TRUE) + z <- seq(min.raw, max.raw, length=length(col)) + image(z = matrix(z, ncol=1), col=col, breaks=breaks, xaxt="n", yaxt="n") + par(usr=c(0, 1, 0, 1)) # needed to draw the histogram correctly + lv <- pretty(breaks) + xv <- scale01(as.numeric(lv), min.raw, max.raw) + axis(1, at=xv, labels=sprintf("%s%%", pretty(lv))) + h <- hist(x, plot=FALSE, breaks=breaks) + hx <- scale01(breaks, min(x), max(x)) + hy <- c(h$counts, h$counts[length(h$counts)]) + lines(hx, hy / max(hy) * 0.95, lwd=2, type="s", col="blue") + axis(2, at=pretty(hy) / max(hy) * 0.95, pretty(hy)) + title(ylab="Count") + title(xlab="Degree of Concentration") + par(op) + invisible(NULL) +} Modified: pkg/PortfolioAnalytics/demo/00Index =================================================================== --- pkg/PortfolioAnalytics/demo/00Index 2014-02-14 03:04:37 UTC (rev 3312) +++ pkg/PortfolioAnalytics/demo/00Index 2014-02-17 02:11:49 UTC (rev 3313) @@ -26,4 +26,4 @@ demo_risk_budgets Demonstrate using risk budget objectives. demo_roi_solvers Demonstrate specifying a solver using ROI. risk_budget_backtesting Demonstrate optimize.portfolio.rebalancing with standard deviation risk budget objective. - +chart_concentration Demonstrate chart.Concentration Added: pkg/PortfolioAnalytics/demo/chart_concentration.R =================================================================== --- pkg/PortfolioAnalytics/demo/chart_concentration.R (rev 0) +++ pkg/PortfolioAnalytics/demo/chart_concentration.R 2014-02-17 02:11:49 UTC (rev 3313) @@ -0,0 +1,63 @@ + +library(PortfolioAnalytics) + +data(edhec) +R <- edhec[, 1:8] +funds <- colnames(R) + +# Construct initial portfolio +init.portf <- portfolio.spec(assets=funds) +init.portf <- add.constraint(portfolio=init.portf, + type="leverage", + min_sum=0.99, + max_sum=1.01) + +init.portf <- add.constraint(portfolio=init.portf, + type="box", + min=0, + max=1) + +init.portf <- add.objective(portfolio=init.portf, + type="return", + name="mean", + multiplier=0) + +init.portf <- add.objective(portfolio=init.portf, + type="risk", + name="ES") + +rb.portf <- add.objective(portfolio=init.portf, + type="risk_budget", + name="ES", + max_prisk=0.4, + arguments=list(p=0.92)) + +# Use DEoptim for optimization +opt <- optimize.portfolio(R=R, + portfolio=init.portf, + optimize_method="random", + search_size=2000, + trace=TRUE) + +opt_rb <- optimize.portfolio(R=R, + portfolio=rb.portf, + optimize_method="random", + search_size=2000, + trace=TRUE) + +# This won't work because opt is not a risk budget optimization +# This should result in an error and not plot anything +chart.Concentration(opt, conc.type="pct_contrib") + +# opt is minimum ES optimization so we can still chart it using weights as +# the measure of concentration +chart.Concentration(opt, conc.type="weights", chart.assets=TRUE, col=heat.colors(10)) +chart.Concentration(opt, conc.type="weights", chart.assets=TRUE, col=bluemono) + +# The concentration is based on the HHI of the percentage component +# contribution to risk +chart.Concentration(opt_rb, conc.type="pct_contrib") + +# The concentration is based on the HHI of the weights +chart.Concentration(opt_rb, conc.type="weights") + Added: pkg/PortfolioAnalytics/man/chart.Concentration.Rd =================================================================== --- pkg/PortfolioAnalytics/man/chart.Concentration.Rd (rev 0) +++ pkg/PortfolioAnalytics/man/chart.Concentration.Rd 2014-02-17 02:11:49 UTC (rev 3313) @@ -0,0 +1,57 @@ +\name{chart.Concentration} +\alias{chart.Concentration} +\title{Classic risk reward scatter and concentration} +\usage{ + chart.Concentration(object, ..., return.col = "mean", + risk.col = "ES", chart.assets = FALSE, + conc.type = c("weights", "pct_contrib"), + col = heat.colors(20), element.color = "darkgray", + cex.axis = 0.8, xlim = NULL, ylim = NULL) +} +\arguments{ + \item{object}{optimal portfolio created by + \code{\link{optimize.portfolio}}.} + + \item{\dots}{any other passthru parameters.} + + \item{return.col}{string matching the objective of a + 'return' objective, on vertical axis.} + + \item{risk.col}{string matching the objective of a 'risk' + objective, on horizontal axis.} + + \item{chart.assets}{TRUE/FALSE. Includes a risk reward + scatter of the assets in the chart.} + + \item{conc.type}{concentration type can be based on the + concentration of weights or concentration of percentage + component contribution to risk (only works with risk + budget objective for the optimization).} + + \item{col}{color palette or vector of colors to use.} + + \item{element.color}{color for the border and axes.} + + \item{cex.axis}{The magnification to be used for axis + annotation relative to the current setting of + \code{cex}.} + + \item{xlim}{set the x-axis limit, same as in + \code{\link{plot}}.} + + \item{ylim}{set the y-axis limit, same as in + \code{\link{plot}}.} +} +\description{ + This function charts the \code{optimize.portfolio} object + in risk-return space and the degree of concentration + based on the weights or percentage component contribution + to risk. +} +\author{ + Peter Carl and Ross Bennett +} +\seealso{ + \code{\link{optimize.portfolio}} +} + From noreply at r-forge.r-project.org Mon Feb 17 03:41:26 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 17 Feb 2014 03:41:26 +0100 (CET) Subject: [Returnanalytics-commits] r3314 - pkg/PortfolioAnalytics/vignettes Message-ID: <20140217024126.AB1A71845D8@r-forge.r-project.org> Author: rossbennett34 Date: 2014-02-17 03:41:25 +0100 (Mon, 17 Feb 2014) New Revision: 3314 Modified: pkg/PortfolioAnalytics/vignettes/risk_budget_optimization.Rnw pkg/PortfolioAnalytics/vignettes/risk_budget_optimization.pdf Log: minor revisions to risk budget optimization vignette to work with new structure of optimize.portfolio.rebalancing objects Modified: pkg/PortfolioAnalytics/vignettes/risk_budget_optimization.Rnw =================================================================== --- pkg/PortfolioAnalytics/vignettes/risk_budget_optimization.Rnw 2014-02-17 02:11:49 UTC (rev 3313) +++ pkg/PortfolioAnalytics/vignettes/risk_budget_optimization.Rnw 2014-02-17 02:41:25 UTC (rev 3314) @@ -321,40 +321,58 @@ out <- optimize.portfolio.rebalancing(R=indexes, portfolio=ObjSpec, optimize_method="DEoptim", search_size=5000, rebalance_on="months", - training_period=nrow(indexes)-1, - traceDE=10) + training_period=nrow(indexes)-10, + traceDE=0) @ -The output of \verb"optimize.portfolio.rebalancing" is a list of objects created by \verb"optimize.portfolio", one for each rebalancing period. +The output of \verb"optimize.portfolio.rebalancing" in the \verb"opt_rebalancing" slot is a list of objects created by \verb"optimize.portfolio", one for each rebalancing period. <>= names(out) -names(out[[1]]) -print(out) +names(out$opt_rebalancing[[1]]) +out @ -The optimal weights for each rebalancing period can be extracted fron the object with the following function: +The \verb"summary" method provides a brief output of the optimization result along with return and risk measures. +<>= +opt.summary <- summary(out) +names(opt.summary) +opt.summary +@ +The optimal weights for each rebalancing period can be extracted fron the object with \verb"extractWeights" and are charted with \verb"chart.Weights". + <>= extractWeights(out) +plot.new() +chart.Weights(out, colorset=bluemono) @ -Also the value of the objective function at each rebalancing period: +Also, the value of the objective function at each rebalancing date is extracted with \verb"extractObjectiveMeasures". <>= -out[[1]]$out -out[[2]]$out +head(extractObjectiveMeasures(out)) @ The first and last observation from the estimation sample: <>= -out[[1]]$data_summary -out[[2]]$data_summary +out$opt_rebalancing[[1]]$data_summary +out$opt_rebalancing[[2]]$data_summary @ +The component contribution to risk at each rebalance date can be charted with \verb"chart.RiskBudget". The component contribution to risk in absolute or percentage. +<>= +plot.new() +chart.RiskBudget(out, match.col="CVaR", risk.type="percentage", col=bluemono) +@ +<>= +plot.new() +chart.RiskBudget(out, match.col="CVaR", risk.type="absolute", col=bluemono) +@ + Of course, DE is a stochastic optimizer and typically will only find a near-optimal solution that depends on the seed. The function \verb"optimize.portfolio.parallel" in \verb"PortfolioAnalytics" allows to run an arbitrary number of portfolio sets in parallel in order to develop "confidence bands" around your solution. It is based on Revolution's \verb"foreach" package \citep{foreach}. \bibliographystyle{abbrvnat} Modified: pkg/PortfolioAnalytics/vignettes/risk_budget_optimization.pdf =================================================================== --- pkg/PortfolioAnalytics/vignettes/risk_budget_optimization.pdf 2014-02-17 02:11:49 UTC (rev 3313) +++ pkg/PortfolioAnalytics/vignettes/risk_budget_optimization.pdf 2014-02-17 02:41:25 UTC (rev 3314) @@ -704,86 +704,372 @@ endstream endobj 118 0 obj << -/Length 1204 +/Length 1054 /Filter /FlateDecode >> stream -x??WKs?F??W??l??x??|?c??\6qQ???"[ H?$?q~??h$?0b#*??p`???????? #?E???>4?r?}?X -`?v -i?\??/?;??xAH?"?SDf? 7?AD?? -???Aj?????!u??????a?? ???j? U??qF???I(?d?0@3??#e3?#?E3-??5??HR???v@????y?+u/k??????WH?.???_Y??4}Id??`n^???w?????n?K ?`???e????f????A2???????ai?3O?R?{c3$d?p?1C???^?4??E???????g???b??F?9|? -%???K???FOv??a?ImV?j?z?????VV?+?p_8 ????[?????m?????R4?p?mV?0}%L:%e???????a???j?4???oe??7S?[??;???????(T ???TA?!.???????cy?S??????9?f????)E????wW???G?~??????????_?????????qG??[???M?P???: +x??VY??F~?W?????????>?????$#???iH??g?1?t? M?4?W???|~??i?a???]??? ?n???X +2?? ???6?`????j???Z??7??U??Ie??????a?? ????P??T?0?2?8??n1??? +??iYc?M??+lb?????kV?????C-?W-????U?7?O??p?>????6s??????x???!????kD [u?o?N?5?"(?Y?]??????~????o???H_??????????k]??? ~.?0??_??Q?x?ST? ]??]?????/??. endstream endobj 121 0 obj << -/Length 621 +/Length 919 /Filter /FlateDecode >> stream -x??V]o?0}???4$:???v\??m????T??]??&KR$??q??%????????^??F?2??m=.??k 3??, *?Vqe???pc????"0p(??J(9??Z??b?%+(??S?ccIM?{>?:}??2?D??8?h?@22J?h?Z''?6?????l??????x???#i?zuN????A????n?k?^??/l,??X????WK??(G5??]??s1??#?x?"???e???yR?i6?  Z ?R?:?Z'??VF^:.?_??O????'??? Y ??j??a???9?}0??)???O:??*H??I????M?b +x??W?o?6?_A?/?P???(?C?$?a??e?A[t?N?D'???E)?????%???s???j?????q+?????^??jc??v?n?)???Tkb?R?$?or??*?lp?????z? +?Na??? d?y +Tg??Vh?l at 6?|?_?oW??%?r?e????S&^??='?`?$l??????}X?O??????? + ???DN????????(??0?L??I?;?pDY/?V*????|9????(?s? +x_?????!???w??_ @?rl????Pz????4?8?8!?W??????mS????!??K?? +y+z +??l>??1)???^Z=? +???M/???^??j??????B?9Ld,?s?n@?D?=?????O??tGC?}s???R?X???*?d?E?????cW\m??I?x?+??????qq?~?????[? +#??D???UB???5B[?7G?Q endstream endobj 124 0 obj << -/Length 892 +/Length 927 /Filter /FlateDecode >> stream -x????o?6???Wi?????<~???a?a??=?A?(r???\?N???;???8sH?^B??t>????0 -R??KsuWN???'??#??aoQ?]?GKg}_}??? ?????V)??7????)7?h?$:*?b?????????S?????&??cb???_??????L?2F?`v+p??V`??Ap?O????W???n?i??????~???,|u[F?u????l_?{Gp??????H?H/Pg?sQ0?f?#v?3???h6?p????a???u??3??:MF?????[???w7tm}wCW??????m???(?ji?7?\?u?TG>??N???????z??|D???cv??????????`??F`?M)???[n ??`?D?]L:C%?o?{??@@ ???A4???q?7O?'??????a?????D?? ??4p??KF0C578??65I?H ?????? +x??VKs?6??W`???:??????4v?N?ie?=$9 e??H???L~}?%Y?X?8?E?????E0?!????????^ +???_????4???t?w?Gk?gD ?0h??R???b???W?Q]?????)c??????0??(?D???s`HqOMS4????????+*2 ??????o?n +?V*??????;su??m]|?s[N?x????i`?????J?? ?????/?O?Ae ???7z? ???C????????b?P???UsW??(?s?e/h?uy?gL ?=?|;????S[??/?O????7'?????euS6n????k?????6??h?>B ?]?6???`s??E?p[?y&=??O =t??u???@?!+_WMs?rg???C?n?g?r8?|%?'??@~?R7??DS?z?h???T,y?g?C {??????y??.??`????2???Pc????\{??>n?9??V??6???W???%(_)?JF?(??????+gr;8 endstream endobj -127 0 obj << -/Length 1468 +128 0 obj << +/Length 481 /Filter /FlateDecode >> stream -x??WK??6??WI??@??S?aN??iR?9%A????ZYt$y?????!??U ??H?p8~??pD02???????k???D0???V?/&'?i)??D?UD ???Q*)?E?"z?k=?9????i;????~T???\??????]ij???R???t?)?v?f??Q?o??>?~\?????????^N??????????V$?Q?1?D$??)??r3?r??TD?R?????V?_???N???]HHuY??Q?(???av??????'E??????&on????h?1Kq??????i,?DOV??J??j?+? '?{?U?M]????>????A?C? ?K?g88?9??@?x??w^????*???Y7?????>?<|??0+?????yY???S???HMS??????76Dte?^?hij ??????+????X???}8G??m?d?i???"G2T????????????????????O??l????ie?/?#?p??????]???_??%$???????g? -[Z at N?7???Ze?q?d???XP??_??^???????????*??/????5E?????V?2????up(!?p?!??r?2??$M?e ,r?[Z???0?4??i?a?^?$???@? ????I,e????{hAg%O???Oc??D??v?u?S_Ax3????:9??????1?$h????????> --}????ey???_6.? ??2E????j??)_???m??_??,???;\??T??aR?*????/??????2?4????b?y?p; +x???Mo?@???+?Kx3?1{??D???,q? ?-RZC?????n??R)q?x4?????????????2?U`?-???]6?4?*?W?????W?Y4???????????? [Nl????>,????7m???dR?N??FB??&:?????????Y?x?+H +???n?G??n=?)p??\?H?X7h?t?y?>??`??e???????l?A??????`?K??uG`??y?[8?bGG??Q??0??H?D4;??l)??o$??$*> stream -x??W_s?8???? -=[??+???'M3????????vgG???WE?Hr??OAy-G??u?E"???O&|r???????????&6????~?????$3"?BNn????O?t??dg?n?????R?z?k???M???:?F?e\{=?9s?k????2V7??T???5-??????+Z??? -?V(Y?=???h_?&eE?s???5???d???'9?????B%6?=??k?/??W??U?8_?:M?D??{?&?????:???;M?N?R??,)mp???"?????)??$?a?????$M?a$a^?!?~^????Re???W???K*??@+?????0??C?*n??H_4k_????d??q?5|?+?ZPiam???????p+ -??T#?????#&??k???=?????s?c??o -??|????(]o???#?|??(????/#?&m???SH???qOc?U?\??7?=,?? ?????+s=??r?&e???BI}.??????_?X[09D?{E -?z?r)`??)???9?RJA???ZT? ??2??S???G?????j?@s?B??]M??Sc?????? ?[???n8?b?{????yi?M??i??!?x:????s?????Jt*h$?C?????E?? +x??UK??0??WX?K"???,?"?b)\?C????n?m????8N?S????vnO??7(??^4?c??:R?j?%???G0Cu???F?T@]p??n? +??? endstream endobj -155 0 obj << +125 0 obj << +/Type /XObject +/Subtype /Form +/FormType 1 +/PTEX.FileName (./figure/unnamed-chunk-26.pdf) +/PTEX.PageNumber 1 +/PTEX.InfoDict 133 0 R +/BBox [0 0 504 504] +/Resources << +/ProcSet [ /PDF /Text ] +/Font << /F2 134 0 R/F3 135 0 R>> +/ExtGState << +>>/ColorSpace << +/sRGB 136 0 R +>>>> +/Length 1475 +/Filter /FlateDecode +>> +stream +x??YKs5???? +?E???; ??? +6???!?Kp?vpl?n=F???4E?Z??z??Z?o???1?>???v??9E?@?c????ew?l????? ?|????h??? ?pY?O?iAm{~?~? ?s??=?j#??}?????78&??? +?`?G?A?T?hl?LOL +?K?A?sP? a??g[?w??? ??,P4i??^??p? ?s +f.R??#?0=F??r +%???Q* ????Q?~??)?@8?K ?m?7K + ?Y????v?)?4??.?? ?%?A.p]Hi????J ?????????T?'????H??2??? $%&R???K*???? ?%?????????#?Q?L???#U@^rt3m)?%?A k??i?r?0??>??????Wu?r{?8??%??b?@???)}? +~3?;???> +stream +x???wTS????7?P????khRH +?H?.*1 J??"6DTpDQ??2(???C??"??Q??D?qp?Id???y?????~k????g?}??????LX ? ?X??????g` ?l?p??B?F?|??l???? ??*????????Y"1P??????\?8=W?%?O???4M?0J?"Y?2V?s?,[|??e9?2?<?s??e???'??9???`???2?&c?tI?@?o??|N6(??.?sSdl-c?(2?-?y?H?_??/X??????Z.$??&\S???????M????07?#?1??Y?rf??Yym?";?8980m-m?(?]????v?^??D???W~? +??e????mi]?P????`/???u}q?|^R??,g+???\K?k)/????C_|?R????ax??8?t1C^7nfz?D????p? ?????u?$??/?ED??L L??[???B?@???????????????X?!@~(* {d+??} ?G???????????}W?L??$?cGD2?Q????Z4 E@?@??????A(?q`1???D ??????`'?u?4?6pt?c?48.??`?R0??)? +?@???R?t C???X??CP?%CBH@??R?????f?[?(t? +C??Qh?z#0 ??Z?l?`O8?????28.????p|??O???X +????:??0?FB?x$ !???i@?????H???[EE1PL? ??????V?6??QP??>?U?(j +?MFk?????t,:??.FW???????8???c?1?L&?????9???a??X?:??? +?r?bl1? +{{{;?}?#?tp?8_\?8??"?Ey?.,?X?????%?%G??1?-??9????????K??l?.??oo???/?O$?&?'=JvM??x??????{????=Vs\?x? ????N???>?u?????c?Kz???=s?/?o?l????|??????y???? ??^d]???p?s?~???:;???/;]??7|?????W????p???????Q?o?H?!?????V????sn??Ys}?????????~4??]? =>?=:?`??;c??'?e??~??!?a???D?#?G?&}'/?^?x?I??????+?\????w?x?20;5?\?????_??????e?t???W?f^??Qs?-?m???w3????+??~???????O?~???? +endstream +endobj +141 0 obj << +/Length 810 +/Filter /FlateDecode +>> +stream +x??VKO?@??W?D?&/3??AP?R-i/E&)?!1???;~?uB?? +E=?????7?Ri? |,o?v?????>1z????v?(?????? 1??I?N1? ?^?Q????D???-p????M;_?t?qO??s?????a?)#Jh%??q!??e??? ?;???t?-g???,]????5?t|nT?t at 0??T???ti?? k?y??B????g?l?*???N?$I?? !???Fh????m????H?~?i8???F??????? +E???.?=N??8?.??n???R?0???8?B??V???ji @?????RA??(gmk?? 9????q??q?Z?M????8?????;n?? ?ds??j"@r?t ?h[?[?"??[?]??\? ???"5??????f????0 Ym?S#(???1???F?a$?(??E[_=?? ???W?Q???zp?|?s????? ?r??F??/?7????z5Y??k????U~????L???j??*?%k/?[???|??:?[Y??S JK)6?:o??1??????HJ???R?}?Mo??rr???h????????8????>I???g??!?y?:5? ?Ng?J???????nZX/Y?*??%D?e?? +?R?????)[N"???C?q; +?e?[????F?c?ba?3Y??????????{?z??O$?x{??/Z?? +ZF??[??Z?gD?????XR +endstream +endobj +145 0 obj << +/Length 700 +/Filter /FlateDecode +>> +stream +x??U?o?0?????D<?>p??!?1 +??!M?5?M?????s??4+?? ??~_~~s!"C????#?z?!?????Q????~ ?}7??Ai??HI??V?\M<.8?4??5???f??`????trz) +2 ??? ???r?1?M??:99I3? I?|N3?dr???MX?????r????????O/???F?\ +?j??M`?1/?*???T?7?U3??????(?96??????$??8M3J$I2? ?Y?q??6 +ND???P??l???5????????e?qb?Oc?1?!?2D?2?)M$p?1?8$?W??????%U?0 l???i? + +??.l?1???Y?a????u +??x???l?*?t?km????I?mQz?E?????? +?????m??????? +?m[?4????????W????q???M?q???'?K4????y?????Q?w ?cB??cBj? +?C6????????]G9/`B|c?? +_?K?????YT????U??\?->?z?uoC#]?\???=?]?F +u?@S?:X??? +??D^?-?^?%???E????=??5???} +???A$:2[n?????c???`0 a|fBB??8:X~?E?????ZK +endstream +endobj +149 0 obj << +/Length 380 +/Filter /FlateDecode +>> +stream +x??T?O?0??W?x?)--?=x?:?7?ez`?mF?A?????b7/??x???>?J??m???????CS??W? + e??8???>$???%??M????}]?{???3^??P??6?e???????p]?9???Ie?????>??P??Lae??????%?C7???e[{??w?????????? } ? +??q?T?5DK??vYQ?m?5~??z?????? f6?i?????????et????toF'?????}?1????:??D*iC/??z??,?q?lHRd?{????????T?J?!\?M???K +endstream +endobj +142 0 obj << +/Type /XObject +/Subtype /Form +/FormType 1 +/PTEX.FileName (./figure/unnamed-chunk-29.pdf) +/PTEX.PageNumber 1 +/PTEX.InfoDict 150 0 R +/BBox [0 0 504 504] +/Resources << +/ProcSet [ /PDF /Text ] +/Font << /F2 151 0 R/F3 152 0 R>> +/ExtGState << +>>/ColorSpace << +/sRGB 153 0 R +>>>> +/Length 1516 +/Filter /FlateDecode +>> +stream +x??YMo?7 ??W?2?9D???c???tC?t;E????.M?b??J?????n????C????")J??Lh?I<,^???R"?NY??f??\?_??A:O?8?? T4?!P??????tE?j???O?mp?????B?? -????B??\+?Z{???$?!?i??jH8????? 3&y? cj??GL? +??AeL4Rm0h?>???c|?!??9?C?LC+\??!?e P??]V?2?2??2?G ???A?Z????B*???N???H?U?aIePt2??MhQ??Aq4S at F:??A&?6?hV?N??Fi?i?S?X?mc?IN#0?p??r?F??n???S?????)??S? +(E?uu>k8N8?j?????A??8?? ??i??7??b9er?,9A`9? ?=??L??4???U?)???T?????$Q@???& ???0$?M????e???qM???d(oqrQ&6G?Uj*O???A???a??GdHe??A:?$f??r??g??Vx?8???0t(eV??e5? ?o??,?,?? +???X? +h?&T ??@??2 +t??"????t?AF?? ?jxRD%M`?96MX?t?i"????psl? :?2??????x?i?TFQL?&?\????D?4W/0????? +3?iFT?8???=??V?Y?_??!N???_????X~]_???g??{?7Q??\v??}??U?^??"l/???G??a*?Ytz?C??.??)????`-??|:??????9?????a??k????????a +?y|:?C??.??)????`-?z|z??????9?????`?k???????a??y|:?Ck?????f??1?bY?S=yyP?t????b???\>{??:??J???????z??)???m1?{c?6?%JC?{fG??Yx&??zz&?kN??J?c?n|}^?> +stream +x???wTS????7?P????khRH +?H?.*1 J??"6DTpDQ??2(???C??"??Q??D?qp?Id???y?????~k????g?}??????LX ? ?X??????g` ?l?p??B?F?|??l???? ??*????????Y"1P??????\?8=W?%?O???4M?0J?"Y?2V?s?,[|??e9?2?<?s??e???'??9???`???2?&c?tI?@?o??|N6(??.?sSdl-c?(2?-?y?H?_??/X??????Z.$??&\S???????M????07?#?1??Y?rf??Yym?";?8980m-m?(?]????v?^??D???W~? +??e????mi]?P????`/???u}q?|^R??,g+???\K?k)/????C_|?R????ax??8?t1C^7nfz?D????p? ?????u?$??/?ED??L L??[???B?@???????????????X?!@~(* {d+??} ?G???????????}W?L??$?cGD2?Q????Z4 E@?@??????A(?q`1???D ??????`'?u?4?6pt?c?48.??`?R0??)? +?@???R?t C???X??CP?%CBH@??R?????f?[?(t? +C??Qh?z#0 ??Z?l?`O8?????28.????p|??O???X +????:??0?FB?x$ !???i@?????H???[EE1PL? ??????V?6??QP??>?U?(j +?MFk?????t,:??.FW???????8???c?1?L&?????9???a??X?:??? +?r?bl1? +{{{;?}?#?tp?8_\?8??"?Ey?.,?X?????%?%G??1?-??9????????K??l?.??oo???/?O$?&?'=JvM??x??????{????=Vs\?x? ????N???>?u?????c?Kz???=s?/?o?l????|??????y???? ??^d]???p?s?~???:;???/;]??7|?????W????p???????Q?o?H?!?????V????sn??Ys}?????????~4??]? =>?=:?`??;c??'?e??~??!?a???D?#?G?&}'/?^?x?I??????+?\????w?x?20;5?\?????_??????e?t???W?f^??Qs?-?m???w3????+??~???????O?~???? +endstream +endobj +158 0 obj << +/Length 881 +/Filter /FlateDecode +>> +stream +x??UKs?6??Wpr)4cBx???l???iG???h??R B??????m??t?????dfuA????? ? f??9?P????f?}.?d?c??ZSd?????]?????f?A????:&??E?? G???o?????????c?3?-p-??????Sc?9??:5?r???A~ k?QA1+?a?,?'??4?)????_O???V ??S?????=???xj t???????<9?P,J?L?S????0??BX??b"?C???4?$G8)?9c87c?k?CoMc??st~???}?3?B? CM???l??????Xh??R8];??QD +z +?7?:(U?? +?`????Nb?,?j????s???l`??/d???,?{???|hf?c? +P?\=$??0_@?A?B ??6?i?.`???E???85?*??B$??? 2??W? FH +z?C8XS 9?X3Yb(%?4??Se??|?/?T????c%.???[ /?6]??c\]???~=?c,? ?:J?b{?7??:??D?P??t8???0? +t?5??%???I????????2&??e?x*tC?b%/?o?_. &kL???}?vz^^? +l?b{6????G??!$A????bm7???????-?*?.M?> +/ExtGState << +>>/ColorSpace << +/sRGB 162 0 R +>>>> +/Length 1545 +/Filter /FlateDecode +>> +stream +x??YKs'????? ??h?v*?JR??????-+)9zD???O??????J??????????F?S&?v?z????B0?4B?ZM??%??????????cv??BG%?=???"7???A?s}??? ?k????J?S??e%?N\9??`RZn5???fNr!??c?JKk?O'c? ??&a>]??/???[4kib???f??47,?ZI?4?f???%]?$?j??YQ??Y?A?????????w<\??????td???Y??? +?3?'?j?????=??=??Z??s1'???5??G????n??@??????y??o??5K`?MTS9>?C9????l?#P?k????@???@??@KO??9???!?]???1???Z???9???_?????,?C?7?`??l ??*:????:???Kw%?h?l9$?.:?K?t?5;d??????ovF??n#?u> +stream +x???wTS????7?P????khRH +?H?.*1 J??"6DTpDQ??2(???C??"??Q??D?qp?Id???y?????~k????g?}??????LX ? ?X??????g` ?l?p??B?F?|??l???? ??*????????Y"1P??????\?8=W?%?O???4M?0J?"Y?2V?s?,[|??e9?2?<?s??e???'??9???`???2?&c?tI?@?o??|N6(??.?sSdl-c?(2?-?y?H?_??/X??????Z.$??&\S???????M????07?#?1??Y?rf??Yym?";?8980m-m?(?]????v?^??D???W~? +??e????mi]?P????`/???u}q?|^R??,g+???\K?k)/????C_|?R????ax??8?t1C^7nfz?D????p? ?????u?$??/?ED??L L??[???B?@???????????????X?!@~(* {d+??} ?G???????????}W?L??$?cGD2?Q????Z4 E@?@??????A(?q`1???D ??????`'?u?4?6pt?c?48.??`?R0??)? +?@???R?t C???X??CP?%CBH@??R?????f?[?(t? +C??Qh?z#0 ??Z?l?`O8?????28.????p|??O???X +????:??0?FB?x$ !???i@?????H???[EE1PL? ??????V?6??QP??>?U?(j +?MFk?????t,:??.FW???????8???c?1?L&?????9???a??X?:??? +?r?bl1? +{{{;?}?#?tp?8_\?8??"?Ey?.,?X?????%?%G??1?-??9????????K??l?.??oo???/?O$?&?'=JvM??x??????{????=Vs\?x? ????N???>?u?????c?Kz???=s?/?o?l????|??????y???? ??^d]???p?s?~???:;???/;]??7|?????W????p???????Q?o?H?!?????V????sn??Ys}?????????~4??]? =>?=:?`??;c??'?e??~??!?a???D?#?G?&}'/?^?x?I??????+?\????w?x?20;5?\?????_??????e?t???W?f^??Qs?-?m???w3????+??~???????O?~???? +endstream +endobj +167 0 obj << +/Length 2072 +/Filter /FlateDecode +>> +stream +x??XMs?8??W??E??( H?U{??O?q??Imm??h ???HI????y?eQ?v6?@??@w??? +FO?`t?&p??????0i_?"???t??2%*??P????yeUNU9??L???x"e?m??xU?>VE^????C????????????z?.?>???d? ??o?????xi?6B?2?????A?sw????$??O?c"?????}l ?w^?????7_???@??]>??qz???????ce?{??I?s??2?N?SF??)C$,??dS??I??????????e?io:?????? I???4[???d?8?tl[7?v???I??p?8???7d??op?!????b????k(?2N LRC9? t??*J???e??????*?Zk?x?Y?0^?????;]??.r??????s??a(}????????????????????D? ????B??O^Z?z?h???-"m?%?????}c????#????X??~"???Eli??????{s?????l +??4?#?e??t?????'???I??????6???w??QG?vf6C?q?????0???!K#?Hqh??????G??57?V.?)}hJ???a??????i?'????o? +a??7??!??B_|W???+L?~na)? ?a??\?{?/???a?B;?d?A~?n?P?????+*?7L?9????.Z ?/????????????J'????k????>??>?:??????????A?????G_;e??8x?i??x??????n?v 0 ?$?"???:??^?????m?w?3??rY?&???f?????y?L?P_G??K NJ<?Y?+????r????y*?d7'?{???:???2?H??f?mn3c,3??U???o?b???|_???* +???2Z????k?????qJ? +?nr??? ?,Y???X?????Ip*??Qy???}?y??q????!??i;n?l?$e????q?do#D????! ??}v?`???E??W^k(?7??n&|B??;?S??(F?? /???P?fc??6? ?p:?f??$?Ac???{w?????K?R?c?h????????OF?7?;????% +,?vKn??? +?S?|5X?J??.t|mm??b??kk?&???????V??C.kK??H?G? 6???T??HD?R? Author: braverock Date: 2014-02-20 13:53:23 +0100 (Thu, 20 Feb 2014) New Revision: 3315 Added: pkg/PerformanceAnalytics/vignettes/ Removed: pkg/PerformanceAnalytics/inst/doc/ Log: - move inst/doc to vignettes From noreply at r-forge.r-project.org Thu Feb 20 15:48:26 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 20 Feb 2014 15:48:26 +0100 (CET) Subject: [Returnanalytics-commits] r3316 - in pkg/PerformanceAnalytics: . R man Message-ID: <20140220144826.BF61818671F@r-forge.r-project.org> Author: braverock Date: 2014-02-20 15:48:26 +0100 (Thu, 20 Feb 2014) New Revision: 3316 Removed: pkg/PerformanceAnalytics/inst/ Modified: pkg/PerformanceAnalytics/DESCRIPTION pkg/PerformanceAnalytics/NAMESPACE pkg/PerformanceAnalytics/R/CAPM.alpha.R pkg/PerformanceAnalytics/R/CAPM.beta.R pkg/PerformanceAnalytics/R/CAPM.dynamic.R pkg/PerformanceAnalytics/R/CAPM.epsilon.R pkg/PerformanceAnalytics/R/CAPM.jensenAlpha.R pkg/PerformanceAnalytics/R/CAPM.utils.R pkg/PerformanceAnalytics/R/checkData.R pkg/PerformanceAnalytics/R/lpm.R pkg/PerformanceAnalytics/man/CAPM.RiskPremium.Rd pkg/PerformanceAnalytics/man/CAPM.alpha.Rd pkg/PerformanceAnalytics/man/CAPM.beta.Rd pkg/PerformanceAnalytics/man/CAPM.dynamic.Rd pkg/PerformanceAnalytics/man/CAPM.epsilon.Rd pkg/PerformanceAnalytics/man/CAPM.jensenAlpha.Rd pkg/PerformanceAnalytics/man/checkData.Rd pkg/PerformanceAnalytics/man/lpm.Rd Log: - add SFM aliases for all CAPM functions, and export them - minor doc edits - bump version as we prepare for new CRAN release Modified: pkg/PerformanceAnalytics/DESCRIPTION =================================================================== --- pkg/PerformanceAnalytics/DESCRIPTION 2014-02-20 12:53:23 UTC (rev 3315) +++ pkg/PerformanceAnalytics/DESCRIPTION 2014-02-20 14:48:26 UTC (rev 3316) @@ -1,7 +1,7 @@ Package: PerformanceAnalytics Type: Package Title: Econometric tools for performance and risk analysis. -Version: 1.1.2 +Version: 1.1.3 Date: $Date$ Author: Peter Carl, Brian G. Peterson Maintainer: Brian G. Peterson Modified: pkg/PerformanceAnalytics/NAMESPACE =================================================================== --- pkg/PerformanceAnalytics/NAMESPACE 2014-02-20 12:53:23 UTC (rev 3315) +++ pkg/PerformanceAnalytics/NAMESPACE 2014-02-20 14:48:26 UTC (rev 3316) @@ -72,6 +72,13 @@ export(Return.read) export(Return.rebalancing) export(Return.relative) +export(SFM.CML) +export(SFM.CML.slope) +export(SFM.alpha) +export(SFM.beta) +export(SFM.dynamic) +export(SFM.epsilon) +export(SFM.jensenAlpha) export(Selectivity) export(SemiDeviation) export(SemiVariance) @@ -200,6 +207,22 @@ export(tim12equal) export(tim6equal) export(tim8equal) +export(tol10qualitative) +export(tol11qualitative) +export(tol12qualitative) +export(tol14rainbow) +export(tol15rainbow) +export(tol18rainbow) +export(tol1qualitative) +export(tol21rainbow) +export(tol2qualitative) +export(tol3qualitative) +export(tol4qualitative) +export(tol5qualitative) +export(tol6qualitative) +export(tol7qualitative) +export(tol8qualitative) +export(tol9qualitative) importFrom(stats,sd) importFrom(utils,packageDescription) importFrom(zoo,rollapply) Modified: pkg/PerformanceAnalytics/R/CAPM.alpha.R =================================================================== --- pkg/PerformanceAnalytics/R/CAPM.alpha.R 2014-02-20 12:53:23 UTC (rev 3315) +++ pkg/PerformanceAnalytics/R/CAPM.alpha.R 2014-02-20 14:48:26 UTC (rev 3316) @@ -1,6 +1,6 @@ -#' calculate CAPM alpha +#' calculate single factor model (CAPM) alpha #' -#' This is a wrapper for calculating a CAPM alpha. +#' This is a wrapper for calculating a single factor model (CAPM) alpha. #' #' "Alpha" purports to be a measure of a manager's skill by measuring the #' portion of the managers returns that are not attributable to "Beta", or the @@ -43,9 +43,10 @@ #' CAPM.alpha(managers[,1:6], #' managers[,8:7,drop=FALSE], #' Rf = managers[,10,drop=FALSE]) -#' -#' @export -CAPM.alpha <- function (Ra, Rb, Rf = 0) +#' +#' @rdname CAPM.alpha +#' @export SFM.alpha CAPM.alpha +CAPM.alpha <- SFM.alpha <- function (Ra, Rb, Rf = 0) { # @author Peter Carl # DESCRIPTION: Modified: pkg/PerformanceAnalytics/R/CAPM.beta.R =================================================================== --- pkg/PerformanceAnalytics/R/CAPM.beta.R 2014-02-20 12:53:23 UTC (rev 3315) +++ pkg/PerformanceAnalytics/R/CAPM.beta.R 2014-02-20 14:48:26 UTC (rev 3316) @@ -1,7 +1,7 @@ -#' calculate CAPM beta +#' calculate single factor model (CAPM) beta #' -#' CAPM Beta is the beta of an asset to the variance and covariance of an -#' initial portfolio. Used to determine diversification potential. +#' The single factor model or CAPM Beta is the beta of an asset to the variance +#' and covariance of an initial portfolio. Used to determine diversification potential. #' #' This function uses a linear intercept model to achieve the same results as #' the symbolic model used by \code{\link{BetaCoVariance}} @@ -83,10 +83,10 @@ #' Rf = managers[, "US 3m TR", drop=FALSE], #' fit="conditional", #' main="Conditional Beta") -#' -#' @export -CAPM.beta <- -function (Ra, Rb, Rf = 0) +#' +#' @rdname CAPM.beta +#' @export CAPM.beta SFM.beta +CAPM.beta <- SFM.beta <- function (Ra, Rb, Rf = 0) { # @author Peter Carl # DESCRIPTION: Modified: pkg/PerformanceAnalytics/R/CAPM.dynamic.R =================================================================== --- pkg/PerformanceAnalytics/R/CAPM.dynamic.R 2014-02-20 12:53:23 UTC (rev 3315) +++ pkg/PerformanceAnalytics/R/CAPM.dynamic.R 2014-02-20 14:48:26 UTC (rev 3316) @@ -1,101 +1,108 @@ -#' Time-varying conditional beta -#' -#' CAPM is estimated assuming that betas and alphas change over time. It is -#' assumed that the market prices of securities fully reflect readily available -#' and public information. A matrix of market information variables, \eqn{Z} -#' measures this information. Possible variables in \eqn{Z} could be the -#' divident yield, Tresaury yield, etc. The betas of stocks and managed -#' portfolios are allowed to change with market conditions: -#' \deqn{\beta_{p}(z_{t})=b_{0p}+B_{p}'z_{t}}{beta(zt) = b0 + Bp'zt} -#' where \eqn{z_{t}=Z_{t}-E[Z]}{zt = Zt - E[Z]} - a normalized vector of the -#' deviations of \eqn{Z_{t}}{Zt}, \eqn{B_{p}}{Bp} - a vector with the same -#' dimension as \eqn{Z_{t}}{Zt}. The coefficient \eqn{b_{0p}}{b0} can be -#' interpreted as the "average beta" or the beta when all infromation variables -#' are at their means. The elements of \eqn{B_{p}}{Bp} measure the sensitivity -#' of the conditional beta to the deviations of the \eqn{Z_{t}}{Zt} from their -#' means. -#' In the similar way the time-varying conditional alpha is modeled: -#' \deqn{\alpha_{pt}=\alpha_{p}(z_{t})=\alpha_{0p}+A_{p}'z_{t}}{alpha(zt) = -#' a0 + Ap'zt} -#' The modified regression is therefore: -#' \deqn{r_{pt+1}=\alpha_{0p}+A_{p}'z_{t}+b_{0p}r_{bt+1}+B_{p}'[z_{t}r_{bt+1}]+ -#' \mu_{pt+1}} -#' -#' @param Ra an xts, vector, matrix, data frame, timeSeries or zoo object of -#' the asset returns -#' @param Rb an xts, vector, matrix, data frame, timeSeries or zoo object of -#' the benchmark asset return -#' @param Rf risk free rate, in same period as your returns -#' @param Z an xts, vector, matrix, data frame, timeSeries or zoo object of -#' k variables that reflect public information -#' @param lags number of lags before the current period on which the alpha and -#' beta are conditioned -#' @param \dots any other passthrough parameters -#' @author Andrii Babii -#' @seealso \code{\link{CAPM.beta}} -#' @references J. Christopherson, D. Carino, W. Ferson. \emph{Portfolio -#' Performance Measurement and Benchmarking}. 2009. McGraw-Hill. Chapter 12. -#' \cr Wayne E. Ferson and Rudi Schadt, "Measuring Fund Strategy and -#' Performance in Changing Economic Conditions," \emph{Journal of Finance}, -#' vol. 51, 1996, pp.425-462 \cr -#' @examples -#' -#' data(managers) -#' CAPM.dynamic(managers[,1,drop=FALSE], managers[,8,drop=FALSE], Rf=.035/12, Z=managers[, 9:10]) -#' CAPM.dynamic(managers[80:120,1:6], managers[80:120,7,drop=FALSE], Rf=managers[80:120,10,drop=FALSE], Z=managers[80:120, 9:10]) -#' CAPM.dynamic(managers[80:120,1:6], managers[80:120,8:7], managers[80:120,10,drop=FALSE], Z=managers[80:120, 9:10]) -#' -#' @export -CAPM.dynamic <- function (Ra, Rb, Rf = 0, Z, lags = 1, ...) -{ # @author Andrii Babii - - # FUNCTION - - Ra = checkData(Ra) - Rb = checkData(Rb) - Z = checkData(Z) - Z = na.omit(Z) - if (!is.null(dim(Rf))) - Rf = checkData(Rf) - Ra.ncols = NCOL(Ra) - Rb.ncols = NCOL(Rb) - pairs = expand.grid(1:Ra.ncols) - - xRa = Return.excess(Ra, Rf)[1:(nrow(Ra) - 1)] - xRb = Return.excess(Rb, Rf)[1:(nrow(Rb) - 1)] - z = Z - matrix(rep(mean(Z), nrow(Z)), nrow(Z), ncol(Z), byrow = TRUE) - # Construct the matrix with information regressors (lagged values) - inform = lag(z) - if (lags > 1){ - for (i in 2:lags) { - inform = cbind(inform, lag(z, i)) - } - } - z = inform[(lags + 1):nrow(z), ] - - dynamic <- function (xRa, xRb, z){ - y = xRa[1:nrow(z)] - X = cbind(z, coredata(xRb[1:nrow(z)]), z * matrix(rep(xRb[1:nrow(z)], ncol(z)), nrow(z), ncol(z))) - X.df = as.data.frame(X) - model = lm(xRa[1:nrow(z)] ~ 1 + ., data = X.df) - return(coef(model)) - } - result = apply(pairs, 1, FUN = function(n, xRa, xRb, z) - dynamic(xRa[, n[1]], xRb[, 1], z), xRa = xRa, xRb = xRb, z = z) - result = t(result) - - if (ncol(Rb) > 1){ - for (i in 2:ncol(xRb)){ - res = apply(pairs, 1, FUN = function(n, xRa, xRb, z) - dynamic(xRa[, n[1]], xRb[, i], z), xRa = xRa, xRb = xRb, z = z) - res = t(res) - result = rbind(result, res) - } - } - - a = paste(rep(colnames(Z), lags), "alpha at t -", expand.grid(1:ncol(Z), 1:lags)[, 2]) - b = paste(rep(colnames(Z), lags), "beta at t -", expand.grid(1:ncol(Z), 1:lags)[, 2]) - colnames(result) = c("Average alpha", a, "Average beta", b) - rownames(result) = paste(rep(colnames(Ra), ncol(Rb)), "to", rep(colnames(Rb), each = ncol(Ra))) - return(result) +#' Time-varying conditional single factor model beta +#' +#' CAPM is estimated assuming that betas and alphas change over time. It is +#' assumed that the market prices of securities fully reflect readily available +#' and public information. A matrix of market information variables, \eqn{Z} +#' measures this information. Possible variables in \eqn{Z} could be the +#' divident yield, Tresaury yield, etc. The betas of stocks and managed +#' portfolios are allowed to change with market conditions: +#' +#' \deqn{\beta_{p}(z_{t})=b_{0p}+B_{p}'z_{t}}{beta(zt) = b0 + Bp'zt} +#' +#' where \eqn{z_{t}=Z_{t}-E[Z]}{zt = Zt - E[Z]} +#' +#' - a normalized vector of the deviations of \eqn{Z_{t}}{Zt}, \eqn{B_{p}}{Bp} +#' +#' - a vector with the same dimension as \eqn{Z_{t}}{Zt}. +#' +#' The coefficient \eqn{b_{0p}}{b0} can be +#' interpreted as the "average beta" or the beta when all infromation variables +#' are at their means. The elements of \eqn{B_{p}}{Bp} measure the sensitivity +#' of the conditional beta to the deviations of the \eqn{Z_{t}}{Zt} from their +#' means. +#' In the similar way the time-varying conditional alpha is modeled: +#' \deqn{\alpha_{pt}=\alpha_{p}(z_{t})=\alpha_{0p}+A_{p}'z_{t}}{alpha(zt) = +#' a0 + Ap'zt} +#' The modified regression is therefore: +#' \deqn{r_{pt+1}=\alpha_{0p}+A_{p}'z_{t}+b_{0p}r_{bt+1}+B_{p}'[z_{t}r_{bt+1}]+ +#' \mu_{pt+1}} +#' +#' @param Ra an xts, vector, matrix, data frame, timeSeries or zoo object of +#' the asset returns +#' @param Rb an xts, vector, matrix, data frame, timeSeries or zoo object of +#' the benchmark asset return +#' @param Rf risk free rate, in same period as your returns +#' @param Z an xts, vector, matrix, data frame, timeSeries or zoo object of +#' k variables that reflect public information +#' @param lags number of lags before the current period on which the alpha and +#' beta are conditioned +#' @param \dots any other passthrough parameters +#' @author Andrii Babii +#' @seealso \code{\link{CAPM.beta}} +#' @references J. Christopherson, D. Carino, W. Ferson. \emph{Portfolio +#' Performance Measurement and Benchmarking}. 2009. McGraw-Hill. Chapter 12. +#' \cr Wayne E. Ferson and Rudi Schadt, "Measuring Fund Strategy and +#' Performance in Changing Economic Conditions," \emph{Journal of Finance}, +#' vol. 51, 1996, pp.425-462 \cr +#' @examples +#' +#' data(managers) +#' CAPM.dynamic(managers[,1,drop=FALSE], managers[,8,drop=FALSE], Rf=.035/12, Z=managers[, 9:10]) +#' CAPM.dynamic(managers[80:120,1:6], managers[80:120,7,drop=FALSE], Rf=managers[80:120,10,drop=FALSE], Z=managers[80:120, 9:10]) +#' CAPM.dynamic(managers[80:120,1:6], managers[80:120,8:7], managers[80:120,10,drop=FALSE], Z=managers[80:120, 9:10]) +#' +#' @rdname CAPM.dynamic +#' @export CAPM.dynamic SFM.dynamic +CAPM.dynamic <- SFM.dynamic <- function (Ra, Rb, Rf = 0, Z, lags = 1, ...) +{ # @author Andrii Babii + + # FUNCTION + + Ra = checkData(Ra) + Rb = checkData(Rb) + Z = checkData(Z) + Z = na.omit(Z) + if (!is.null(dim(Rf))) + Rf = checkData(Rf) + Ra.ncols = NCOL(Ra) + Rb.ncols = NCOL(Rb) + pairs = expand.grid(1:Ra.ncols) + + xRa = Return.excess(Ra, Rf)[1:(nrow(Ra) - 1)] + xRb = Return.excess(Rb, Rf)[1:(nrow(Rb) - 1)] + z = Z - matrix(rep(mean(Z), nrow(Z)), nrow(Z), ncol(Z), byrow = TRUE) + # Construct the matrix with information regressors (lagged values) + inform = lag(z) + if (lags > 1){ + for (i in 2:lags) { + inform = cbind(inform, lag(z, i)) + } + } + z = inform[(lags + 1):nrow(z), ] + + dynamic <- function (xRa, xRb, z){ + y = xRa[1:nrow(z)] + X = cbind(z, coredata(xRb[1:nrow(z)]), z * matrix(rep(xRb[1:nrow(z)], ncol(z)), nrow(z), ncol(z))) + X.df = as.data.frame(X) + model = lm(xRa[1:nrow(z)] ~ 1 + ., data = X.df) + return(coef(model)) + } + result = apply(pairs, 1, FUN = function(n, xRa, xRb, z) + dynamic(xRa[, n[1]], xRb[, 1], z), xRa = xRa, xRb = xRb, z = z) + result = t(result) + + if (ncol(Rb) > 1){ + for (i in 2:ncol(xRb)){ + res = apply(pairs, 1, FUN = function(n, xRa, xRb, z) + dynamic(xRa[, n[1]], xRb[, i], z), xRa = xRa, xRb = xRb, z = z) + res = t(res) + result = rbind(result, res) + } + } + + a = paste(rep(colnames(Z), lags), "alpha at t -", expand.grid(1:ncol(Z), 1:lags)[, 2]) + b = paste(rep(colnames(Z), lags), "beta at t -", expand.grid(1:ncol(Z), 1:lags)[, 2]) + colnames(result) = c("Average alpha", a, "Average beta", b) + rownames(result) = paste(rep(colnames(Ra), ncol(Rb)), "to", rep(colnames(Rb), each = ncol(Ra))) + return(result) } \ No newline at end of file Modified: pkg/PerformanceAnalytics/R/CAPM.epsilon.R =================================================================== --- pkg/PerformanceAnalytics/R/CAPM.epsilon.R 2014-02-20 12:53:23 UTC (rev 3315) +++ pkg/PerformanceAnalytics/R/CAPM.epsilon.R 2014-02-20 14:48:26 UTC (rev 3316) @@ -22,15 +22,15 @@ #' @examples #' #' data(portfolio_bacon) -#' print(CAPM.epsilon(portfolio_bacon[,1], portfolio_bacon[,2])) #expected -0.013 +#' print(SFM.epsilon(portfolio_bacon[,1], portfolio_bacon[,2])) #expected -0.013 #' #' data(managers) -#' print(CAPM.epsilon(managers['1996',1], managers['1996',8])) -#' print(CAPM.epsilon(managers['1996',1:5], managers['1996',8])) +#' print(SFM.epsilon(managers['1996',1], managers['1996',8])) +#' print(SFM.epsilon(managers['1996',1:5], managers['1996',8])) #' -#' @export - -CAPM.epsilon <- +#' @rdname CAPM.epsilon +#' @export CAPM.epsilon SFM.epsilon +CAPM.epsilon <- SFM.epsilon <- function (Ra, Rb, Rf = 0, ...) { Ra = checkData(Ra, method="matrix") Modified: pkg/PerformanceAnalytics/R/CAPM.jensenAlpha.R =================================================================== --- pkg/PerformanceAnalytics/R/CAPM.jensenAlpha.R 2014-02-20 12:53:23 UTC (rev 3315) +++ pkg/PerformanceAnalytics/R/CAPM.jensenAlpha.R 2014-02-20 14:48:26 UTC (rev 3316) @@ -22,15 +22,16 @@ #' @examples #' #' data(portfolio_bacon) -#' print(CAPM.jensenAlpha(portfolio_bacon[,1], portfolio_bacon[,2])) #expected -0.014 +#' print(SFM.jensenAlpha(portfolio_bacon[,1], portfolio_bacon[,2])) #expected -0.014 #' #' data(managers) -#' print(CAPM.jensenAlpha(managers['1996',1], managers['1996',8])) -#' print(CAPM.jensenAlpha(managers['1996',1:5], managers['1996',8])) +#' print(SFM.jensenAlpha(managers['1996',1], managers['1996',8])) +#' print(SFM.jensenAlpha(managers['1996',1:5], managers['1996',8])) #' -#' @export +#' @rdname CAPM.jensenAlpha +#' @export CAPM.jensenAlpha SFM.jensenAlpha -CAPM.jensenAlpha <- +CAPM.jensenAlpha <- SFM.jensenAlpha <- function (Ra, Rb, Rf = 0, ...) { calcul = FALSE Modified: pkg/PerformanceAnalytics/R/CAPM.utils.R =================================================================== --- pkg/PerformanceAnalytics/R/CAPM.utils.R 2014-02-20 12:53:23 UTC (rev 3315) +++ pkg/PerformanceAnalytics/R/CAPM.utils.R 2014-02-20 14:48:26 UTC (rev 3316) @@ -2,8 +2,8 @@ # CAPM.alpha and CAPM.beta could probably have gone in here too, but they're already in separate files #' @rdname CAPM.RiskPremium -#' @export -CAPM.CML.slope <- function (Rb, Rf = 0 ) +#' @export CAPM.CML.slope SFM.CML.slope +CAPM.CML.slope <- SFM.CML.slope <- function (Rb, Rf = 0 ) { #author Brian G. Peterson #the Capital Market Line slope is a wrapper for the Sharpe Ratio on the benchmark asset @@ -16,8 +16,8 @@ } #' @rdname CAPM.RiskPremium -#' @export -CAPM.CML <- function (Ra, Rb, Rf = 0) +#' @export CAPM.CML SFM.CML +CAPM.CML <- SFM.CML <-function (Ra, Rb, Rf = 0) { #@author Brian G. Peterson Ra = checkData(Ra) @@ -50,13 +50,18 @@ -#' utility functions for CAPM CML, SML, and RiskPremium +#' utility functions for single factor (CAPM) CML, SML, and RiskPremium #' #' The Capital Asset Pricing Model, from which the popular #' \code{\link{SharpeRatio}} is derived, is a theory of market equilibrium. #' These utility functions provide values for various measures proposed in the #' CAPM. #' +#' At it's core, the CAPM is a single factor linear model. In light of +#' the general ustility and wide use of single factor model, all +#' functions in the CAPM suite will also be available with SFM (single factor model) +#' prefixes. +#' #' The CAPM provides a justification for passive or index investing by positing #' that assets that are not on the efficient frontier will either rise or lower #' in price until they are on the efficient frontier of the market portfolio. @@ -87,22 +92,22 @@ #' Chapter 7 of Ruppert(2004) gives an extensive overview of CAPM, its #' assumptions and deficiencies. #' -#' \code{CAPM.RiskPremium} is the premium returned to the investor over the +#' \code{SFM.RiskPremium} is the premium returned to the investor over the #' risk free asset #' #' \deqn{\overline{(R_{a}-R_{f})}}{mean(Ra-Rf=0)} #' -#' \code{CAPM.CML} calculates the expected return of the asset against the +#' \code{SFM.CML} calculates the expected return of the asset against the #' benchmark Capital Market Line #' -#' \code{CAPM.CML.slope} calculates the slope of the Capital Market Line for +#' \code{SFM.CML.slope} calculates the slope of the Capital Market Line for #' looking at how a particular asset compares to the CML #' -#' \code{CAPM.SML.slope} calculates the slope of the Security Market Line for +#' \code{SFM.SML.slope} calculates the slope of the Security Market Line for #' looking at how a particular asset compares to the SML created by the #' benchmark #' -#' @aliases CAPM.utils CAPM.RiskPremium CAPM.CML CAPM.CML.slope CAPM.SML.slope +#' @aliases CAPM.utils CAPM.RiskPremium CAPM.CML CAPM.CML.slope CAPM.SML.slope SFM.utils SFM.RiskPremium SFM.CML SFM.CML.slope SFM.SML.slope #' @param Ra an xts, vector, matrix, data frame, timeSeries or zoo object of #' asset returns #' @param Rb return vector of the benchmark asset Modified: pkg/PerformanceAnalytics/R/checkData.R =================================================================== --- pkg/PerformanceAnalytics/R/checkData.R 2014-02-20 12:53:23 UTC (rev 3315) +++ pkg/PerformanceAnalytics/R/checkData.R 2014-02-20 14:48:26 UTC (rev 3316) @@ -3,8 +3,8 @@ #' This function was created to make the different kinds of data classes at #' least \emph{seem} more fungible. It allows the user to pass in a data #' object without being concerned that the function requires a matrix, -#' data.frame, or timeSeries object. By using this, the function "knows" what -#' data format it has to work with. +#' data.frame, vector, xts, or timeSeries object. By using \code{checkData}, +#' the function "knows" what data format it has to work with. #' #' #' @param x a vector, matrix, data.frame, xts, timeSeries or zoo object to be @@ -13,7 +13,7 @@ #' @param quiet TRUE/FALSE if false, it will throw warnings when errors are #' noticed, default TRUE #' @param method type of coerced data object to return, one of -#' c("zoo","matrix","vector"), default "zoo" +#' c("xts", "zoo", "data.frame", "matrix", "vector"), default "xts" #' @param \dots any other passthru parameters #' @author Peter Carl #' @keywords ts multivariate distribution models Modified: pkg/PerformanceAnalytics/R/lpm.R =================================================================== --- pkg/PerformanceAnalytics/R/lpm.R 2014-02-20 12:53:23 UTC (rev 3315) +++ pkg/PerformanceAnalytics/R/lpm.R 2014-02-20 14:48:26 UTC (rev 3316) @@ -1,16 +1,23 @@ -#' calculate the lower partial moment of a time series +#' calculate a lower partial moment for a time series +#' +#' Caclulate a Lower Partial Moment around the mean or a specified threshold. +#' +#' Lower partial moments capture negative deviation from a reference point. +#' That reference point may be the mean, or some specified threshold that +#' has other meaning for the investor. +#' +#' @references Huffman S.P. & Moll C.R., +#' "The impact of Asymmetry on Expected Stock Returns: An Investigation of Alternative Risk Measures", +#' Algorithmic Finance 1, 2011 p. 79-93 #' -#' Code to calculate the Lower Partion Moments around the mean or a specified threshold -#' from Huffman S,P & Moll C.R. 2011 "The impact of Asymmetry on Expected Stock Returns: An Investigation of Alternative Risk Measures" Algorithmic Finance 1 (2011) 79-93 -#' #' @param R xts data #' @param n the n-th moment to return #' @param threshold threshold can be the mean or any point as desired #' @param about_mean TRUE/FALSE calculate LPM about the mean under the threshold or use the threshold to calculate the LPM around (if FALSE) #' -#' @author Kyle Balkissoon /email{kylebalkissoon at gmail.com} /email{kyle at corporateknights.com} +#' @author Kyle Balkissoon \email{kylebalkisoon@@gmail.com} #' @export -lpm <- function(R,n,threshold,about_mean=FALSE){ +lpm <- function(R,n=2,threshold=0,about_mean=FALSE){ if(about_mean==TRUE){ #Calculate Number of obs less than threshold Modified: pkg/PerformanceAnalytics/man/CAPM.RiskPremium.Rd =================================================================== --- pkg/PerformanceAnalytics/man/CAPM.RiskPremium.Rd 2014-02-20 12:53:23 UTC (rev 3315) +++ pkg/PerformanceAnalytics/man/CAPM.RiskPremium.Rd 2014-02-20 14:48:26 UTC (rev 3316) @@ -4,7 +4,12 @@ \alias{CAPM.RiskPremium} \alias{CAPM.SML.slope} \alias{CAPM.utils} -\title{utility functions for CAPM CML, SML, and RiskPremium} +\alias{SFM.CML} +\alias{SFM.CML.slope} +\alias{SFM.RiskPremium} +\alias{SFM.SML.slope} +\alias{SFM.utils} +\title{utility functions for single factor (CAPM) CML, SML, and RiskPremium} \usage{ CAPM.CML.slope(Rb, Rf = 0) @@ -29,6 +34,11 @@ values for various measures proposed in the CAPM. } \details{ + At it's core, the CAPM is a single factor linear model. + In light of the general ustility and wide use of single + factor model, all functions in the CAPM suite will also + be available with SFM (single factor model) prefixes. + The CAPM provides a justification for passive or index investing by positing that assets that are not on the efficient frontier will either rise or lower in price @@ -68,21 +78,21 @@ Chapter 7 of Ruppert(2004) gives an extensive overview of CAPM, its assumptions and deficiencies. - \code{CAPM.RiskPremium} is the premium returned to the + \code{SFM.RiskPremium} is the premium returned to the investor over the risk free asset \deqn{\overline{(R_{a}-R_{f})}}{mean(Ra-Rf=0)} - \code{CAPM.CML} calculates the expected return of the + \code{SFM.CML} calculates the expected return of the asset against the benchmark Capital Market Line - \code{CAPM.CML.slope} calculates the slope of the Capital + \code{SFM.CML.slope} calculates the slope of the Capital Market Line for looking at how a particular asset compares to the CML - \code{CAPM.SML.slope} calculates the slope of the - Security Market Line for looking at how a particular - asset compares to the SML created by the benchmark + \code{SFM.SML.slope} calculates the slope of the Security + Market Line for looking at how a particular asset + compares to the SML created by the benchmark } \examples{ data(managers) Modified: pkg/PerformanceAnalytics/man/CAPM.alpha.Rd =================================================================== --- pkg/PerformanceAnalytics/man/CAPM.alpha.Rd 2014-02-20 12:53:23 UTC (rev 3315) +++ pkg/PerformanceAnalytics/man/CAPM.alpha.Rd 2014-02-20 14:48:26 UTC (rev 3316) @@ -1,6 +1,6 @@ \name{CAPM.alpha} \alias{CAPM.alpha} -\title{calculate CAPM alpha} +\title{calculate single factor model (CAPM) alpha} \usage{ CAPM.alpha(Ra, Rb, Rf = 0) } @@ -13,7 +13,8 @@ \item{Rf}{risk free rate, in same period as your returns} } \description{ - This is a wrapper for calculating a CAPM alpha. + This is a wrapper for calculating a single factor model + (CAPM) alpha. } \details{ "Alpha" purports to be a measure of a manager's skill by Modified: pkg/PerformanceAnalytics/man/CAPM.beta.Rd =================================================================== --- pkg/PerformanceAnalytics/man/CAPM.beta.Rd 2014-02-20 12:53:23 UTC (rev 3315) +++ pkg/PerformanceAnalytics/man/CAPM.beta.Rd 2014-02-20 14:48:26 UTC (rev 3316) @@ -3,7 +3,7 @@ \alias{CAPM.beta.bear} \alias{CAPM.beta.bull} \alias{TimingRatio} -\title{calculate CAPM beta} +\title{calculate single factor model (CAPM) beta} \usage{ CAPM.beta(Ra, Rb, Rf = 0) @@ -22,9 +22,9 @@ \item{Rf}{risk free rate, in same period as your returns} } \description{ - CAPM Beta is the beta of an asset to the variance and - covariance of an initial portfolio. Used to determine - diversification potential. + The single factor model or CAPM Beta is the beta of an + asset to the variance and covariance of an initial + portfolio. Used to determine diversification potential. } \details{ This function uses a linear intercept model to achieve Modified: pkg/PerformanceAnalytics/man/CAPM.dynamic.Rd =================================================================== --- pkg/PerformanceAnalytics/man/CAPM.dynamic.Rd 2014-02-20 12:53:23 UTC (rev 3315) +++ pkg/PerformanceAnalytics/man/CAPM.dynamic.Rd 2014-02-20 14:48:26 UTC (rev 3316) @@ -1,70 +1,78 @@ -\name{CAPM.dynamic} -\alias{CAPM.dynamic} -\title{Time-varying conditional beta} -\usage{ - CAPM.dynamic(Ra, Rb, Rf = 0, Z, lags = 1, ...) -} -\arguments{ - \item{Ra}{an xts, vector, matrix, data frame, timeSeries - or zoo object of the asset returns} - - \item{Rb}{an xts, vector, matrix, data frame, timeSeries - or zoo object of the benchmark asset return} - - \item{Rf}{risk free rate, in same period as your returns} - - \item{Z}{an xts, vector, matrix, data frame, timeSeries - or zoo object of k variables that reflect public - information} - - \item{lags}{number of lags before the current period on - which the alpha and beta are conditioned} - - \item{\dots}{any other passthrough parameters} -} -\description{ - CAPM is estimated assuming that betas and alphas change - over time. It is assumed that the market prices of - securities fully reflect readily available and public - information. A matrix of market information variables, - \eqn{Z} measures this information. Possible variables in - \eqn{Z} could be the divident yield, Tresaury yield, etc. - The betas of stocks and managed portfolios are allowed to - change with market conditions: - \deqn{\beta_{p}(z_{t})=b_{0p}+B_{p}'z_{t}}{beta(zt) = b0 - + Bp'zt} where \eqn{z_{t}=Z_{t}-E[Z]}{zt = Zt - E[Z]} - a - normalized vector of the deviations of \eqn{Z_{t}}{Zt}, - \eqn{B_{p}}{Bp} - a vector with the same dimension as - \eqn{Z_{t}}{Zt}. The coefficient \eqn{b_{0p}}{b0} can be - interpreted as the "average beta" or the beta when all - infromation variables are at their means. The elements of - \eqn{B_{p}}{Bp} measure the sensitivity of the - conditional beta to the deviations of the \eqn{Z_{t}}{Zt} - from their means. In the similar way the time-varying - conditional alpha is modeled: - \deqn{\alpha_{pt}=\alpha_{p}(z_{t})=\alpha_{0p}+A_{p}'z_{t}}{alpha(zt) - = a0 + Ap'zt} The modified regression is therefore: - \deqn{r_{pt+1}=\alpha_{0p}+A_{p}'z_{t}+b_{0p}r_{bt+1}+B_{p}'[z_{t}r_{bt+1}]+ - \mu_{pt+1}} -} -\examples{ -data(managers) -CAPM.dynamic(managers[,1,drop=FALSE], managers[,8,drop=FALSE], Rf=.035/12, Z=managers[, 9:10]) -CAPM.dynamic(managers[80:120,1:6], managers[80:120,7,drop=FALSE], Rf=managers[80:120,10,drop=FALSE], Z=managers[80:120, 9:10]) -CAPM.dynamic(managers[80:120,1:6], managers[80:120,8:7], managers[80:120,10,drop=FALSE], Z=managers[80:120, 9:10]) -} -\author{ - Andrii Babii -} -\references{ - J. Christopherson, D. Carino, W. Ferson. \emph{Portfolio - Performance Measurement and Benchmarking}. 2009. - McGraw-Hill. Chapter 12. \cr Wayne E. Ferson and Rudi - Schadt, "Measuring Fund Strategy and Performance in - Changing Economic Conditions," \emph{Journal of Finance}, - vol. 51, 1996, pp.425-462 \cr -} -\seealso{ - \code{\link{CAPM.beta}} -} - +\name{CAPM.dynamic} +\alias{CAPM.dynamic} +\title{Time-varying conditional single factor model beta} +\usage{ + CAPM.dynamic(Ra, Rb, Rf = 0, Z, lags = 1, ...) +} +\arguments{ + \item{Ra}{an xts, vector, matrix, data frame, timeSeries + or zoo object of the asset returns} + + \item{Rb}{an xts, vector, matrix, data frame, timeSeries + or zoo object of the benchmark asset return} + + \item{Rf}{risk free rate, in same period as your returns} + + \item{Z}{an xts, vector, matrix, data frame, timeSeries + or zoo object of k variables that reflect public + information} + + \item{lags}{number of lags before the current period on + which the alpha and beta are conditioned} + + \item{\dots}{any other passthrough parameters} +} +\description{ + CAPM is estimated assuming that betas and alphas change + over time. It is assumed that the market prices of + securities fully reflect readily available and public + information. A matrix of market information variables, + \eqn{Z} measures this information. Possible variables in + \eqn{Z} could be the divident yield, Tresaury yield, etc. + The betas of stocks and managed portfolios are allowed to + change with market conditions: +} +\details{ + \deqn{\beta_{p}(z_{t})=b_{0p}+B_{p}'z_{t}}{beta(zt) = b0 + + Bp'zt} + + where \eqn{z_{t}=Z_{t}-E[Z]}{zt = Zt - E[Z]} + + - a normalized vector of the deviations of + \eqn{Z_{t}}{Zt}, \eqn{B_{p}}{Bp} + + - a vector with the same dimension as \eqn{Z_{t}}{Zt}. + + The coefficient \eqn{b_{0p}}{b0} can be interpreted as + the "average beta" or the beta when all infromation + variables are at their means. The elements of + \eqn{B_{p}}{Bp} measure the sensitivity of the + conditional beta to the deviations of the \eqn{Z_{t}}{Zt} + from their means. In the similar way the time-varying + conditional alpha is modeled: + \deqn{\alpha_{pt}=\alpha_{p}(z_{t})=\alpha_{0p}+A_{p}'z_{t}}{alpha(zt) + = a0 + Ap'zt} The modified regression is therefore: + \deqn{r_{pt+1}=\alpha_{0p}+A_{p}'z_{t}+b_{0p}r_{bt+1}+B_{p}'[z_{t}r_{bt+1}]+ + \mu_{pt+1}} +} +\examples{ +data(managers) +CAPM.dynamic(managers[,1,drop=FALSE], managers[,8,drop=FALSE], Rf=.035/12, Z=managers[, 9:10]) +CAPM.dynamic(managers[80:120,1:6], managers[80:120,7,drop=FALSE], Rf=managers[80:120,10,drop=FALSE], Z=managers[80:120, 9:10]) +CAPM.dynamic(managers[80:120,1:6], managers[80:120,8:7], managers[80:120,10,drop=FALSE], Z=managers[80:120, 9:10]) +} +\author{ + Andrii Babii +} +\references{ + J. Christopherson, D. Carino, W. Ferson. \emph{Portfolio + Performance Measurement and Benchmarking}. 2009. + McGraw-Hill. Chapter 12. \cr Wayne E. Ferson and Rudi + Schadt, "Measuring Fund Strategy and Performance in + Changing Economic Conditions," \emph{Journal of Finance}, + vol. 51, 1996, pp.425-462 \cr +} +\seealso{ + \code{\link{CAPM.beta}} +} + Modified: pkg/PerformanceAnalytics/man/CAPM.epsilon.Rd =================================================================== --- pkg/PerformanceAnalytics/man/CAPM.epsilon.Rd 2014-02-20 12:53:23 UTC (rev 3315) +++ pkg/PerformanceAnalytics/man/CAPM.epsilon.Rd 2014-02-20 14:48:26 UTC (rev 3316) @@ -31,11 +31,11 @@ } \examples{ data(portfolio_bacon) -print(CAPM.epsilon(portfolio_bacon[,1], portfolio_bacon[,2])) #expected -0.013 +print(SFM.epsilon(portfolio_bacon[,1], portfolio_bacon[,2])) #expected -0.013 data(managers) -print(CAPM.epsilon(managers['1996',1], managers['1996',8])) -print(CAPM.epsilon(managers['1996',1:5], managers['1996',8])) +print(SFM.epsilon(managers['1996',1], managers['1996',8])) +print(SFM.epsilon(managers['1996',1:5], managers['1996',8])) } \author{ Matthieu Lestel Modified: pkg/PerformanceAnalytics/man/CAPM.jensenAlpha.Rd =================================================================== --- pkg/PerformanceAnalytics/man/CAPM.jensenAlpha.Rd 2014-02-20 12:53:23 UTC (rev 3315) +++ pkg/PerformanceAnalytics/man/CAPM.jensenAlpha.Rd 2014-02-20 14:48:26 UTC (rev 3316) @@ -30,11 +30,11 @@ } \examples{ data(portfolio_bacon) -print(CAPM.jensenAlpha(portfolio_bacon[,1], portfolio_bacon[,2])) #expected -0.014 +print(SFM.jensenAlpha(portfolio_bacon[,1], portfolio_bacon[,2])) #expected -0.014 data(managers) -print(CAPM.jensenAlpha(managers['1996',1], managers['1996',8])) -print(CAPM.jensenAlpha(managers['1996',1:5], managers['1996',8])) +print(SFM.jensenAlpha(managers['1996',1], managers['1996',8])) +print(SFM.jensenAlpha(managers['1996',1:5], managers['1996',8])) } \author{ Matthieu Lestel Modified: pkg/PerformanceAnalytics/man/checkData.Rd =================================================================== --- pkg/PerformanceAnalytics/man/checkData.Rd 2014-02-20 12:53:23 UTC (rev 3315) +++ pkg/PerformanceAnalytics/man/checkData.Rd 2014-02-20 14:48:26 UTC (rev 3316) @@ -17,7 +17,8 @@ [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3316 From noreply at r-forge.r-project.org Thu Feb 20 18:07:25 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 20 Feb 2014 18:07:25 +0100 (CET) Subject: [Returnanalytics-commits] r3317 - in pkg/PerformanceAnalytics: . R man sandbox Message-ID: <20140220170725.B7E86186AB8@r-forge.r-project.org> Author: braverock Date: 2014-02-20 18:07:25 +0100 (Thu, 20 Feb 2014) New Revision: 3317 Added: pkg/PerformanceAnalytics/man/HurstIndex.Rd pkg/PerformanceAnalytics/sandbox/Return.wealthindex.R Removed: pkg/PerformanceAnalytics/R/Return.index.R pkg/PerformanceAnalytics/R/Return.wealthindex.R Modified: pkg/PerformanceAnalytics/NAMESPACE pkg/PerformanceAnalytics/R/ActivePremium.R pkg/PerformanceAnalytics/R/HurstIndex.R pkg/PerformanceAnalytics/R/mean.utils.R pkg/PerformanceAnalytics/R/zerofill.R Log: - export more functions prior to CRAN release - move Return.index/wealthindex to sandbox Modified: pkg/PerformanceAnalytics/NAMESPACE =================================================================== --- pkg/PerformanceAnalytics/NAMESPACE 2014-02-20 14:48:26 UTC (rev 3316) +++ pkg/PerformanceAnalytics/NAMESPACE 2014-02-20 17:07:25 UTC (rev 3317) @@ -1,11 +1,8 @@ -S3method(mean,LCL) -S3method(mean,UCL) -S3method(mean,geometric) -S3method(mean,stderr) S3method(textplot,character) S3method(textplot,data.frame) S3method(textplot,default) S3method(textplot,matrix) +export(ActivePremium) export(ActiveReturn) export(AdjustedSharpeRatio) export(AppraisalRatio) @@ -43,6 +40,7 @@ export(ETL) export(FamaBeta) export(Frequency) +export(HurstIndex) export(InformationRatio) export(Kappa) export(KellyRatio) @@ -166,6 +164,10 @@ export(macro.dates) export(macro.labels) export(maxDrawdown) +export(mean.LCL) +export(mean.UCL) +export(mean.geometric) +export(mean.stderr) export(opensymbols) export(rainbow10equal) export(rainbow12equal) Modified: pkg/PerformanceAnalytics/R/ActivePremium.R =================================================================== --- pkg/PerformanceAnalytics/R/ActivePremium.R 2014-02-20 14:48:26 UTC (rev 3316) +++ pkg/PerformanceAnalytics/R/ActivePremium.R 2014-02-20 17:07:25 UTC (rev 3317) @@ -29,7 +29,7 @@ #' @aliases #' ActivePremium #' ActiveReturn -#' @export +#' @export ActiveReturn ActivePremium ActiveReturn <- ActivePremium <- function (Ra, Rb, scale = NA) { # @author Peter Carl Modified: pkg/PerformanceAnalytics/R/HurstIndex.R =================================================================== --- pkg/PerformanceAnalytics/R/HurstIndex.R 2014-02-20 14:48:26 UTC (rev 3316) +++ pkg/PerformanceAnalytics/R/HurstIndex.R 2014-02-20 17:07:25 UTC (rev 3317) @@ -1,38 +1,50 @@ +#' calculate the Hurst Index +#' The Hurst index can be used to measure whether returns are mean reverting, +#' totally random, or persistent. +#' +#' Hurst obtained a dimensionless statistical exponent by dividing the range +#' by the standard deviation of the observations, +#' so this approach is commonly referred to as rescaled range (R/S) analysis. +#' +#' \deqn{H = log(m)/log(n)} +#' +#' where +#' \eqn{m = [max(r_i) - min(r_i)]/sigma_p} and +#' \eqn{n = number of observations} +# +#' A Hurst index between 0.5 and 1 suggests that the returns are persistent. +#' At 0.5, the index suggests returns are totally random. Between 0 and 0.5 +#' it suggests that the returns are mean reverting. +#' +#' H.E. Hurst originally developed the Hurst index to help establish optimal +#' water storage along the Nile. Nile floods are extremely persistent, +#' measuring a Hurst index of 0.9. Peters (1991) notes that Equity markets +#' have a Hurst index in excess of 0.5, with typical values of around 0.7. +#' That appears to be anomalous in the context of the mainstream 'rational +#' behaviour' theories of economics, and suggests existence of a powerful +#' 'long-term memory' causal dependence. Clarkson (2001) suggests that an +#' 'over-reaction bias' could be expected to generate a powerful 'long-term +#' memory' effect in share prices. +#' +#' @param R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns +#' @param \dots any other passthru parameters +#' @references +#' Clarkson, R. (2001) FARM: a financial actuarial risk model. In Chapter +#' 12 of Managing Downside Risk in Financial Markets, F. Sortino and S. +#' +#' Satchel. Butterworth-Heinemann Finance. +#' +#' Peters, E.E (1991) Chaos and Order in Capital Markets, New York: Wiley. +#' +#' Bacon, Carl. (2008) Practical Portfolio Performance Measurement and Attribution, 2nd Edition. London: John Wiley & Sons. +#' +#' @export HurstIndex <- function (R, ...) { - # The Hurst index can be used to measure whether returns are mean reverting, - # totally random, or persistent. Hurst obtained a dimensionless statistical - # exponent by dividing the range by the standard deviation of the - # observations, so this approach is generally referred to as rescaled range - # (R/S) analysis. - # - # H = log(m)/log(n) where - # m = [max(r_i) - min(r_i)]/sigma_p - # n = number of observations - # - # A Hurst index between 0.5 and 1 suggests that the returns are persistent. - # At 0.5, the index suggests returns are totally random. Between 0 and 0.5 - # it suggests that the returns are mean reverting. - # - # H.E. Hurst originally developed the Hurst index to help establish optimal - # water storage along the Nile. Nile floods are extremely persistent, - # measuring a Hurst index of 0.9. Peters (1991) notes that Equity markets - # have a Hurst index in excess of 0.5, with typical values of around 0.7. - # That appears to be anomalous in the context of the mainstream 'rational - # behaviour' theories of economics, and suggests existence of a powerful - # 'long-term memory' causal dependence. Clarkson (2001) suggests that an - # 'over-reaction bias' could be expected to generate a powerful 'long-term - # memory' effect in share prices. - # - # Clarkson, R. (2001) FARM: a financial actuarial risk model. In Chapter - # 12 of Managing Downside Risk in Financial Markets, F. Sortino and S. - # Satchel. Butterworth-Heinemann Finance. - # Peters, E.E (1991) Chaos and Order in Capital Markets, New York: Wiley. - # Bacon, Carl. (2008) Practical Portfolio Performance Measurement and - # Attribution, 2nd Edition. London: John Wiley & Sons. + R = checkData(R) rs <- function(R) { Deleted: pkg/PerformanceAnalytics/R/Return.index.R =================================================================== --- pkg/PerformanceAnalytics/R/Return.index.R 2014-02-20 14:48:26 UTC (rev 3316) +++ pkg/PerformanceAnalytics/R/Return.index.R 2014-02-20 17:07:25 UTC (rev 3317) @@ -1,54 +0,0 @@ -Return.index <- -function (R, wealth.index = TRUE, ...) -{ # @author Peter Carl - - # DESCRIPTION: - # Cumulates the returns given as a cumulative return or a "wealth index". - - # Inputs: - # R: a matrix, data frame, or timeSeries of returns - # wealth.index: if true, shows the "value of $1", starting the cumulation - # of returns at 1 rather than zero - - # Outputs: - # A timeseries line chart of the cumulative return series - - # FUNCTION: - - # Transform input data to a matrix - x = checkData(R) - - # Get dimensions and labels - columns = ncol(x) - columnnames = colnames(x) - - # Calculate the cumulative return - one = 0 - if(!wealth.index) - one = 1 - - for(column in 1:columns) { - column.Return.cumulative = na.skip(x[,column,drop=FALSE],FUN = function(x,one) {cumprod(1+x) - one},one=one) - if(column == 1) - Return.cumulative = column.Return.cumulative - else - Return.cumulative = merge(Return.cumulative,column.Return.cumulative) - } - if(columns == 1) - Return.cumulative = as.xts(Return.cumulative) - colnames(Return.cumulative) = columnnames - reclass(Return.cumulative,match.to=x) - -} - -############################################################################### -# R (http://r-project.org/) Econometrics for Performance and Risk Analysis -# -# Copyright (c) 2004-2014 Peter Carl and Brian G. Peterson -# -# This R package is distributed under the terms of the GNU Public License (GPL) -# for full details see the file COPYING -# -# $Id$ -# -############################################################################### \ No newline at end of file Deleted: pkg/PerformanceAnalytics/R/Return.wealthindex.R =================================================================== --- pkg/PerformanceAnalytics/R/Return.wealthindex.R 2014-02-20 14:48:26 UTC (rev 3316) +++ pkg/PerformanceAnalytics/R/Return.wealthindex.R 2014-02-20 17:07:25 UTC (rev 3317) @@ -1,54 +0,0 @@ -Return.wealthindex <- -function (R, wealth.index = TRUE, ...) -{ # @author Peter Carl - - # DESCRIPTION: - # Cumulates the returns given as a cumulative return or a "wealth index". - - # Inputs: - # R: a matrix, data frame, or timeSeries of returns - # wealth.index: if true, shows the "value of $1", starting the cumulation - # of returns at 1 rather than zero - - # Outputs: - # A timeseries line chart of the cumulative return series - - # FUNCTION: - - # Transform input data to a matrix - x = checkData(R) - - # Get dimensions and labels - columns = ncol(x) - columnnames = colnames(x) - - # Calculate the cumulative return - one = 0 - if(!wealth.index) - one = 1 - - for(column in 1:columns) { - column.Return.cumulative = na.skip(x[,column,drop=FALSE],FUN = function(x,one) {cumprod(1+x) - one},one=one) - if(column == 1) - Return.cumulative = column.Return.cumulative - else - Return.cumulative = merge(Return.cumulative,column.Return.cumulative) - } - if(columns == 1) - Return.cumulative = as.xts(Return.cumulative) - colnames(Return.cumulative) = columnnames - reclass(Return.cumulative,match.to=x) - -} - -############################################################################### -# R (http://r-project.org/) Econometrics for Performance and Risk Analysis -# -# Copyright (c) 2004-2014 Peter Carl and Brian G. Peterson -# -# This R package is distributed under the terms of the GNU Public License (GPL) -# for full details see the file COPYING -# -# $Id$ -# -############################################################################### \ No newline at end of file Modified: pkg/PerformanceAnalytics/R/mean.utils.R =================================================================== --- pkg/PerformanceAnalytics/R/mean.utils.R 2014-02-20 14:48:26 UTC (rev 3316) +++ pkg/PerformanceAnalytics/R/mean.utils.R 2014-02-20 17:07:25 UTC (rev 3317) @@ -31,7 +31,7 @@ #' mean.LCL(edhec[,"Funds of Funds"]) #' @rdname mean.geometric #' @method mean geometric -#' @export +#' @export mean.geometric mean.geometric <- function (x, ...) {# @author Peter Carl @@ -63,7 +63,7 @@ #' @rdname mean.geometric #' @method mean stderr -#' @export +#' @export mean.stderr mean.stderr <- function (x, ...) {# @author Peter Carl @@ -95,7 +95,7 @@ #' @rdname mean.geometric #' @method mean LCL -#' @export +#' @export mean.LCL mean.LCL <- function (x, ci = 0.95, ...) {# @author Peter Carl @@ -134,7 +134,7 @@ #' @rdname mean.geometric #' @method mean UCL -#' @export +#' @export mean.UCL mean.UCL <- function (x, ci = 0.95, ...) {# @author Peter Carl Modified: pkg/PerformanceAnalytics/R/zerofill.R =================================================================== --- pkg/PerformanceAnalytics/R/zerofill.R 2014-02-20 14:48:26 UTC (rev 3316) +++ pkg/PerformanceAnalytics/R/zerofill.R 2014-02-20 17:07:25 UTC (rev 3317) @@ -25,6 +25,7 @@ #' that this will skew your results. #' #' @param x time series to zero fill +#' @export zerofill <- function (x) { mat<-checkData(x,"matrix") for(column in 1:ncol(mat)){ Added: pkg/PerformanceAnalytics/man/HurstIndex.Rd =================================================================== --- pkg/PerformanceAnalytics/man/HurstIndex.Rd (rev 0) +++ pkg/PerformanceAnalytics/man/HurstIndex.Rd 2014-02-20 17:07:25 UTC (rev 3317) @@ -0,0 +1,57 @@ +\name{HurstIndex} +\alias{HurstIndex} +\title{calculate the Hurst Index +The Hurst index can be used to measure whether returns are mean reverting, +totally random, or persistent.} +\usage{ + HurstIndex(R, ...) +} +\arguments{ + \item{R}{an xts, vector, matrix, data frame, timeSeries + or zoo object of asset returns} + + \item{\dots}{any other passthru parameters} +} +\description{ + Hurst obtained a dimensionless statistical exponent by + dividing the range by the standard deviation of the + observations, so this approach is commonly referred to as + rescaled range (R/S) analysis. +} +\details{ + \deqn{H = log(m)/log(n)} + + where \eqn{m = [max(r_i) - min(r_i)]/sigma_p} and \eqn{n + = number of observations} A Hurst index between 0.5 and 1 + suggests that the returns are persistent. At 0.5, the + index suggests returns are totally random. Between 0 and + 0.5 it suggests that the returns are mean reverting. + + H.E. Hurst originally developed the Hurst index to help + establish optimal water storage along the Nile. Nile + floods are extremely persistent, measuring a Hurst index + of 0.9. Peters (1991) notes that Equity markets have a + Hurst index in excess of 0.5, with typical values of + around 0.7. That appears to be anomalous in the context + of the mainstream 'rational behaviour' theories of + economics, and suggests existence of a powerful + 'long-term memory' causal dependence. Clarkson (2001) + suggests that an 'over-reaction bias' could be expected + to generate a powerful 'long-term memory' effect in share + prices. +} +\references{ + Clarkson, R. (2001) FARM: a financial actuarial risk + model. In Chapter 12 of Managing Downside Risk in + Financial Markets, F. Sortino and S. + + Satchel. Butterworth-Heinemann Finance. + + Peters, E.E (1991) Chaos and Order in Capital Markets, + New York: Wiley. + + Bacon, Carl. (2008) Practical Portfolio Performance + Measurement and Attribution, 2nd Edition. London: John + Wiley & Sons. +} + Copied: pkg/PerformanceAnalytics/sandbox/Return.wealthindex.R (from rev 3315, pkg/PerformanceAnalytics/R/Return.wealthindex.R) =================================================================== --- pkg/PerformanceAnalytics/sandbox/Return.wealthindex.R (rev 0) +++ pkg/PerformanceAnalytics/sandbox/Return.wealthindex.R 2014-02-20 17:07:25 UTC (rev 3317) @@ -0,0 +1,54 @@ +Return.wealthindex <- +function (R, wealth.index = TRUE, ...) +{ # @author Peter Carl + + # DESCRIPTION: + # Cumulates the returns given as a cumulative return or a "wealth index". + + # Inputs: + # R: a matrix, data frame, or timeSeries of returns + # wealth.index: if true, shows the "value of $1", starting the cumulation + # of returns at 1 rather than zero + + # Outputs: + # A timeseries line chart of the cumulative return series + + # FUNCTION: + + # Transform input data to a matrix + x = checkData(R) + + # Get dimensions and labels + columns = ncol(x) + columnnames = colnames(x) + + # Calculate the cumulative return + one = 0 + if(!wealth.index) + one = 1 + + for(column in 1:columns) { + column.Return.cumulative = na.skip(x[,column,drop=FALSE],FUN = function(x,one) {cumprod(1+x) - one},one=one) + if(column == 1) + Return.cumulative = column.Return.cumulative + else + Return.cumulative = merge(Return.cumulative,column.Return.cumulative) + } + if(columns == 1) + Return.cumulative = as.xts(Return.cumulative) + colnames(Return.cumulative) = columnnames + reclass(Return.cumulative,match.to=x) + +} + +############################################################################### +# R (http://r-project.org/) Econometrics for Performance and Risk Analysis +# +# Copyright (c) 2004-2014 Peter Carl and Brian G. Peterson +# +# This R package is distributed under the terms of the GNU Public License (GPL) +# for full details see the file COPYING +# +# $Id$ +# +############################################################################### \ No newline at end of file From noreply at r-forge.r-project.org Thu Feb 20 19:24:48 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 20 Feb 2014 19:24:48 +0100 (CET) Subject: [Returnanalytics-commits] r3318 - in pkg/PortfolioAnalytics: . R demo man Message-ID: <20140220182448.31C89186716@r-forge.r-project.org> Author: rossbennett34 Date: 2014-02-20 19:24:47 +0100 (Thu, 20 Feb 2014) New Revision: 3318 Added: pkg/PortfolioAnalytics/demo/multiple_portfolio_optimization.R pkg/PortfolioAnalytics/man/combine.portfolios.Rd Modified: pkg/PortfolioAnalytics/NAMESPACE pkg/PortfolioAnalytics/R/extractstats.R pkg/PortfolioAnalytics/R/generics.R pkg/PortfolioAnalytics/R/optimize.portfolio.R pkg/PortfolioAnalytics/R/utility.combine.R pkg/PortfolioAnalytics/demo/00Index Log: Adding functionality to handle multiple portfolio objects for optimization Modified: pkg/PortfolioAnalytics/NAMESPACE =================================================================== --- pkg/PortfolioAnalytics/NAMESPACE 2014-02-20 17:07:25 UTC (rev 3317) +++ pkg/PortfolioAnalytics/NAMESPACE 2014-02-20 18:24:47 UTC (rev 3318) @@ -12,6 +12,7 @@ export(chart.Weights.EF) export(chart.Weights) export(combine.optimizations) +export(combine.portfolios) export(constrained_objective_v2) export(constrained_objective) export(constraint_ROI) @@ -46,7 +47,6 @@ export(optimize.portfolio) export(portfolio_risk_objective) export(portfolio.spec) -export(portfolios.combine) export(pos_limit_fail) export(position_limit_constraint) export(quadratic_utility_objective) @@ -99,9 +99,12 @@ S3method(chart.Weights.EF,efficient.frontier) S3method(chart.Weights.EF,optimize.portfolio) S3method(extractObjectiveMeasures,opt.list) +S3method(extractObjectiveMeasures,opt.rebal.list) S3method(extractObjectiveMeasures,optimize.portfolio.rebalancing) S3method(extractObjectiveMeasures,optimize.portfolio) S3method(extractObjectiveMeasures,summary.optimize.portfolio.rebalancing) +S3method(extractStats,opt.list) +S3method(extractStats,opt.rebal.list) S3method(extractStats,optimize.portfolio.DEoptim) S3method(extractStats,optimize.portfolio.eqwt) S3method(extractStats,optimize.portfolio.GenSA) @@ -112,6 +115,7 @@ S3method(extractStats,optimize.portfolio.rebalancing) S3method(extractStats,optimize.portfolio.ROI) S3method(extractWeights,opt.list) +S3method(extractWeights,opt.rebal.list) S3method(extractWeights,optimize.portfolio.rebalancing) S3method(extractWeights,optimize.portfolio) S3method(extractWeights,summary.optimize.portfolio.rebalancing) @@ -123,12 +127,15 @@ S3method(plot,optimize.portfolio) S3method(print,constraint) S3method(print,efficient.frontier) +S3method(print,opt.list) +S3method(print,opt.rebal.list) S3method(print,optimize.portfolio.DEoptim) S3method(print,optimize.portfolio.GenSA) S3method(print,optimize.portfolio.pso) S3method(print,optimize.portfolio.random) S3method(print,optimize.portfolio.rebalancing) S3method(print,optimize.portfolio.ROI) +S3method(print,portfolio.list) S3method(print,portfolio) S3method(print,summary.optimize.portfolio.rebalancing) S3method(print,summary.optimize.portfolio) Modified: pkg/PortfolioAnalytics/R/extractstats.R =================================================================== --- pkg/PortfolioAnalytics/R/extractstats.R 2014-02-20 17:07:25 UTC (rev 3317) +++ pkg/PortfolioAnalytics/R/extractstats.R 2014-02-20 18:24:47 UTC (rev 3318) @@ -595,3 +595,54 @@ return(out) } +#' @method extractStats opt.list +#' @S3method extractStats opt.list +#' @export +extractStats.opt.list <- function(object, ...){ + # get the stats of each optimization in a list + # each element in the list is an optimize.portfolio object + stats_list <- vector("list", length(object)) + for(i in 1:length(stats_list)){ + stats_list[[i]] <- extractStats(object[[i]]) + } + return(stats_list) +} + +#' @method extractWeights opt.rebal.list +#' @S3method extractWeights opt.rebal.list +#' @export +extractWeights.opt.rebal.list <- function(object, ...){ + # get the optimal weights of each optimization in a list + # each element in the list is an optimize.portfolio.rebalancing object + weights_list <- vector("list", length(object)) + for(i in 1:length(weights_list)){ + weights_list[[i]] <- extractWeights(object[[i]]) + } + return(weights_list) +} + +#' @method extractObjectiveMeasures opt.rebal.list +#' @S3method extractObjectiveMeasures opt.rebal.list +#' @export +extractObjectiveMeasures.opt.rebal.list <- function(object, ...){ + # get the optimal weights of each optimization in a list + # each element in the list is an optimize.portfolio.rebalancing object + obj_list <- vector("list", length(object)) + for(i in 1:length(obj_list)){ + obj_list[[i]] <- extractObjectiveMeasures(object[[i]]) + } + return(obj_list) +} + +#' @method extractStats opt.rebal.list +#' @S3method extractStats opt.rebal.list +#' @export +extractStats.opt.rebal.list <- function(object, ...){ + # get the stats of each optimization in a list + # each element in the list is an optimize.portfolio.rebalancing object + stats_list <- vector("list", length(object)) + for(i in 1:length(stats_list)){ + stats_list[[i]] <- extractStats(object[[i]]) + } + return(stats_list) +} Modified: pkg/PortfolioAnalytics/R/generics.R =================================================================== --- pkg/PortfolioAnalytics/R/generics.R 2014-02-20 17:07:25 UTC (rev 3317) +++ pkg/PortfolioAnalytics/R/generics.R 2014-02-20 18:24:47 UTC (rev 3318) @@ -962,3 +962,33 @@ invisible(list(weights=wts, metrics=riskret)) } +#' @method print portfolio.list +#' @S3method print portfolio.list +#' @export +print.portfolio.list <- function(x, ...){ + for(i in 1:length(x)){ + cat("Portfolio ", i, "\n", sep="") + print(x[[i]]) + } +} + +#' @method print opt.list +#' @S3method print opt.list +#' @export +print.opt.list <- function(x, ...){ + for(i in 1:length(x)){ + cat("Optimization ", i, "\n", sep="") + print(x[[i]]) + } +} + +#' @method print opt.rebal.list +#' @S3method print opt.rebal.list +#' @export +print.opt.rebal.list <- function(x, ...){ + for(i in 1:length(x)){ + cat("Optimization ", i, "\n", sep="") + print(x[[i]]) + } +} + Modified: pkg/PortfolioAnalytics/R/optimize.portfolio.R =================================================================== --- pkg/PortfolioAnalytics/R/optimize.portfolio.R 2014-02-20 17:07:25 UTC (rev 3317) +++ pkg/PortfolioAnalytics/R/optimize.portfolio.R 2014-02-20 18:24:47 UTC (rev 3318) @@ -446,6 +446,36 @@ message=FALSE ) { + # This is the case where the user has passed in a list of portfolio objects + # for the portfolio argument. + # Loop through the portfolio list and recursively call optimize.portfolio + # Note that I return at the end of this block. I know it is not good practice + # to return before the end of a function, but I am not sure of another way + # to handle a list of portfolio objects with the recursive call to + # optimize.portfolio. + if(inherits(portfolio, "portfolio.list")){ + n.portf <- length(portfolio) + opt.list <- vector("list", n.portf) + for(i in 1:length(opt.list)){ + if(message) cat("Starting optimization of portfolio ", i, "\n") + opt.list[[i]] <- optimize.portfolio(R=R, + portfolio=portfolio[[i]], + constraints=constraints, + objectives=objectives, + optimize_method=optimize_method, + search_size=search_size, + trace=trace, + ...=..., + rp=rp, + momentFUN=momentFUN, + message=message) + } + out <- combine.optimizations(opt.list) + ##### return here for portfolio.list because this is a recursive call + ##### for optimize.portfolio + return(out) + } + optimize_method <- optimize_method[1] tmptrace <- NULL start_t <- Sys.time() @@ -1246,6 +1276,40 @@ stopifnot("package:foreach" %in% search() || require("foreach",quietly=TRUE)) stopifnot("package:iterators" %in% search() || require("iterators",quietly=TRUE)) + # This is the case where the user has passed in a list of portfolio objects + # for the portfolio argument. + # Loop through the portfolio list and recursively call + # optimize.portfolio.rebalancing. + #Note that I return at the end of this block. I know it is not good practice + # to return before the end of a function, but I am not sure of another way + # to handle a list of portfolio objects with the recursive call to + # optimize.portfolio. + if(inherits(portfolio, "portfolio.list")){ + n.portf <- length(portfolio) + opt.list <- vector("list", n.portf) + for(i in 1:length(opt.list)){ + if(hasArg(message)) message=match.call(expand.dots=TRUE)$message else message=FALSE + if(message) cat("Starting optimization of portfolio ", i, "\n") + opt.list[[i]] <- optimize.portfolio.rebalancing(R=R, + portfolio=portfolio[[i]], + constraints=constraints, + objectives=objectives, + optimize_method=optimize_method, + search_size=search_size, + trace=trace, + ...=..., + rp=rp, + rebalance_on=rebalance_on, + training_period=training_period, + trailing_periods=trailing_periods) + } + out <- combine.optimizations(opt.list) + class(out) <- "opt.rebal.list" + ##### return here for portfolio.list because this is a recursive call + ##### for optimize.portfolio.rebalancing + return(out) + } + # Store the call to return later call <- match.call() @@ -1255,6 +1319,8 @@ stop("you must pass in an object of class 'portfolio' to control the optimization") } + if(hasArg(message)) message=match.call(expand.dots=TRUE)$message else message=FALSE + # Check for constraints and objectives passed in separately outside of the portfolio object if(!is.null(constraints)){ if(inherits(constraints, "v1_constraint")){ @@ -1307,8 +1373,8 @@ names(out_list)<-index(R[ep.i]) end_t <- Sys.time() - # message(c("overall elapsed time:",end_t-start_t)) elapsed_time <- end_t - start_t + if(message) message(c("overall elapsed time:", end_t-start_t)) # out object to return out <- list() Modified: pkg/PortfolioAnalytics/R/utility.combine.R =================================================================== --- pkg/PortfolioAnalytics/R/utility.combine.R 2014-02-20 17:07:25 UTC (rev 3317) +++ pkg/PortfolioAnalytics/R/utility.combine.R 2014-02-20 18:24:47 UTC (rev 3318) @@ -11,13 +11,15 @@ combine.optimizations <- function(x){ if(!is.list(x)) stop("x must be passed in as a list") for(i in 1:length(x)){ - if(!inherits(x[[i]], "optimize.portfolio")) stop("All objects in x must be of class 'optimize.portfolio'") + if(!(inherits(x[[i]], "optimize.portfolio") | inherits(x[[i]], "optimize.portfolio.rebalancing"))){ + stop("All objects in x must be of class 'optimize.portfolio' or 'optimize.portfolio.rebalancing'") + } } class(x) <- "opt.list" return(x) } -#' Combine objects created by portfolio +#' Combine a list of portfolio objects #' #' This function takes a list of objects created by \code{\link{portfolio.spec}} #' and sets the class name attribute to 'portfolio.list' for use in generic functions @@ -25,12 +27,12 @@ #' @param x a list of objects created by \code{\link{portfolio.spec}} #' @return a \code{portfolio.list} object #' @export -portfolios.combine <- function(x){ +combine.portfolios <- function(x){ if(!is.list(x)) stop("x must be passed in as a list") for(i in 1:length(x)){ if(!inherits(x[[i]], "portfolio")) stop("All objects in x must be of class 'portfolio'") } - class(x) <- "portfolio.list" + class(x) <- c("portfolio.list", "portfolio") return(x) } Modified: pkg/PortfolioAnalytics/demo/00Index =================================================================== --- pkg/PortfolioAnalytics/demo/00Index 2014-02-20 17:07:25 UTC (rev 3317) +++ pkg/PortfolioAnalytics/demo/00Index 2014-02-20 18:24:47 UTC (rev 3318) @@ -27,3 +27,4 @@ demo_roi_solvers Demonstrate specifying a solver using ROI. risk_budget_backtesting Demonstrate optimize.portfolio.rebalancing with standard deviation risk budget objective. chart_concentration Demonstrate chart.Concentration +multiple_portfolio_optimization Demonstrate passing a list of portfolios to optimize.portfolio and optimize.portfolio.rebalancing \ No newline at end of file Added: pkg/PortfolioAnalytics/demo/multiple_portfolio_optimization.R =================================================================== --- pkg/PortfolioAnalytics/demo/multiple_portfolio_optimization.R (rev 0) +++ pkg/PortfolioAnalytics/demo/multiple_portfolio_optimization.R 2014-02-20 18:24:47 UTC (rev 3318) @@ -0,0 +1,74 @@ + +library(PortfolioAnalytics) + +# Examples of passing a list portfolio objects to optimize.portfolio and +# optimize.portfolio.rebalancing + +data(edhec) +R <- edhec[, 1:4] +funds <- colnames(R) + +# Construct initial portfolio +init.portf <- portfolio.spec(assets=funds) +init.portf <- add.constraint(portfolio=init.portf, type="weight_sum", + min_sum=0.99, max_sum=1.01) +init.portf <- add.constraint(portfolio=init.portf, type="long_only") + +# Minimize portfolio standard deviation +minSD.portf <- add.objective(portfolio=init.portf, type="risk", name="StdDev") + +# Maximize mean return per unit portfolio standard deviation +meanSD.portf <- add.objective(portfolio=minSD.portf, type="return", name="mean") + +# Minimize expected shortfall +minES.portf <- add.objective(portfolio=init.portf, type="risk", name="ES") + +# Maximize mean return per unit portfolio expected shortfall +meanES.portf <- add.objective(portfolio=minES.portf, type="return", name="mean") + +# Combine the portfolios +mult.portf <- combine.portfolios(list(minSD.portf, meanSD.portf, minES.portf, meanES.portf)) +mult.portf + +# run the optimization for mult.portf +mult.opt <- optimize.portfolio(R, mult.portf, optimize_method="random", + search_size=2000, trace=TRUE, message = TRUE) + +class(mult.opt) +mult.opt + +# This combines the weights for each portfolio optimized +extractWeights(mult.opt) + +# This combines the objective measures for each portfolio +extractObjectiveMeasures(mult.opt) + +# For N portfolios, this returns a list of length N with the stats +# for each portfolio +opt.xtract <- extractStats(mult.opt) + +# Run the rebalancing optimization for mult.portf +mult.opt.rebal <- optimize.portfolio.rebalancing(R, mult.portf, + optimize_method="random", + search_size=2000, + trace=TRUE, + message=TRUE, + rebalance_on="quarters", + training_period=140) + +class(mult.opt.rebal) +mult.opt.rebal + +# For N portfolios, this returns a list of length N with the optimal weights +# at each rebalancing date +extractWeights(mult.opt.rebal) + +# For N portfolios, this returns a list of length N with the objective measures +# at each rebalancing date +extractObjectiveMeasures(mult.opt.rebal) + +# For N portfolios, this returns a list of length N with the stats +# for each portfolio +opt.rebal.xtract <- extractStats(mult.opt.rebal) + + Added: pkg/PortfolioAnalytics/man/combine.portfolios.Rd =================================================================== --- pkg/PortfolioAnalytics/man/combine.portfolios.Rd (rev 0) +++ pkg/PortfolioAnalytics/man/combine.portfolios.Rd 2014-02-20 18:24:47 UTC (rev 3318) @@ -0,0 +1,20 @@ +\name{combine.portfolios} +\alias{combine.portfolios} +\title{Combine a list of portfolio objects} +\usage{ + combine.portfolios(x) +} +\arguments{ + \item{x}{a list of objects created by + \code{\link{portfolio.spec}}} +} +\value{ + a \code{portfolio.list} object +} +\description{ + This function takes a list of objects created by + \code{\link{portfolio.spec}} and sets the class name + attribute to 'portfolio.list' for use in generic + functions +} + From noreply at r-forge.r-project.org Thu Feb 20 23:49:06 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 20 Feb 2014 23:49:06 +0100 (CET) Subject: [Returnanalytics-commits] r3319 - pkg/PortfolioAnalytics/R Message-ID: <20140220224906.7B17E186A6F@r-forge.r-project.org> Author: rossbennett34 Date: 2014-02-20 23:49:06 +0100 (Thu, 20 Feb 2014) New Revision: 3319 Modified: pkg/PortfolioAnalytics/R/charts.efficient.frontier.R Log: Modifying chart.EfficientFrontierOverlay to use portfolio.list Modified: pkg/PortfolioAnalytics/R/charts.efficient.frontier.R =================================================================== --- pkg/PortfolioAnalytics/R/charts.efficient.frontier.R 2014-02-20 18:24:47 UTC (rev 3318) +++ pkg/PortfolioAnalytics/R/charts.efficient.frontier.R 2014-02-20 22:49:06 UTC (rev 3319) @@ -518,7 +518,8 @@ #' Overlay the efficient frontiers of multiple portfolio objects on a single plot. #' #' @param R an xts object of asset returns -#' @param portfolio_list list of portfolio objects created by \code{\link{portfolio.spec}} +#' @param portfolio_list list of portfolio objects created by +#' \code{\link{portfolio.spec}} and combined with \code{\link{combine.portfolios}} #' @param type type of efficient frontier, see \code{\link{create.EfficientFrontier}} #' @param n.portfolios number of portfolios to extract along the efficient frontier. #' This is only used for objects of class \code{optimize.portfolio} @@ -545,7 +546,7 @@ #' @export chart.EfficientFrontierOverlay <- function(R, portfolio_list, type, n.portfolios=25, match.col="ES", search_size=2000, main="Efficient Frontiers", cex.axis=0.8, element.color="darkgray", legend.loc=NULL, legend.labels=NULL, cex.legend=0.8, xlim=NULL, ylim=NULL, ..., chart.assets=TRUE, labels.assets=TRUE, pch.assets=21, cex.assets=0.8, col=NULL, lty=NULL, lwd=NULL){ # create multiple efficient frontier objects (one per portfolio in portfolio_list) - if(!is.list(portfolio_list)) stop("portfolio_list must be passed in as a list") + if(!inherits(portfolio_list, "portfolio.list")) stop("portfolio_list must be passed in as a list") if(length(portfolio_list) == 1) warning("Only one portfolio object in portfolio_list") # store in out out <- list() From noreply at r-forge.r-project.org Thu Feb 20 23:56:08 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 20 Feb 2014 23:56:08 +0100 (CET) Subject: [Returnanalytics-commits] r3320 - in pkg/PortfolioAnalytics: demo vignettes Message-ID: <20140220225608.68447186B6D@r-forge.r-project.org> Author: rossbennett34 Date: 2014-02-20 23:56:08 +0100 (Thu, 20 Feb 2014) New Revision: 3320 Modified: pkg/PortfolioAnalytics/demo/00Index pkg/PortfolioAnalytics/vignettes/ROI_vignette.pdf Log: adding end of line to demo/00Index and minor edit to ROI vignette Modified: pkg/PortfolioAnalytics/demo/00Index =================================================================== --- pkg/PortfolioAnalytics/demo/00Index 2014-02-20 22:49:06 UTC (rev 3319) +++ pkg/PortfolioAnalytics/demo/00Index 2014-02-20 22:56:08 UTC (rev 3320) @@ -27,4 +27,4 @@ demo_roi_solvers Demonstrate specifying a solver using ROI. risk_budget_backtesting Demonstrate optimize.portfolio.rebalancing with standard deviation risk budget objective. chart_concentration Demonstrate chart.Concentration -multiple_portfolio_optimization Demonstrate passing a list of portfolios to optimize.portfolio and optimize.portfolio.rebalancing \ No newline at end of file +multiple_portfolio_optimization Demonstrate passing a list of portfolios to optimize.portfolio and optimize.portfolio.rebalancing Modified: pkg/PortfolioAnalytics/vignettes/ROI_vignette.pdf =================================================================== (Binary files differ) From noreply at r-forge.r-project.org Fri Feb 21 00:02:14 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 21 Feb 2014 00:02:14 +0100 (CET) Subject: [Returnanalytics-commits] r3321 - in pkg/PortfolioAnalytics: R sandbox Message-ID: <20140220230214.7F0A5186C6D@r-forge.r-project.org> Author: rossbennett34 Date: 2014-02-21 00:02:12 +0100 (Fri, 21 Feb 2014) New Revision: 3321 Added: pkg/PortfolioAnalytics/sandbox/testing_max_starr_sharpe.R Modified: pkg/PortfolioAnalytics/R/optFUN.R pkg/PortfolioAnalytics/R/optimize.portfolio.R Log: Modifying how maximum sharpe and maximum starr ratio are calculated for ROI. Previously using a binary search I wrote, now using optimize() so it is more robust and easier to maintain. Modified: pkg/PortfolioAnalytics/R/optFUN.R =================================================================== --- pkg/PortfolioAnalytics/R/optFUN.R 2014-02-20 22:56:08 UTC (rev 3320) +++ pkg/PortfolioAnalytics/R/optFUN.R 2014-02-20 23:02:12 UTC (rev 3321) @@ -937,19 +937,13 @@ return(out) } - -mean_etl_opt <- function(R, constraints, moments, target, alpha, solver="glpk", tol=.Machine$double.eps^0.5, maxit=50){ - # This function returns the target mean return that maximizes mean / etl (i.e. starr) +# This function uses optimize() to find the target return value that +# results in the maximum starr ratio (mean / ES). +# returns the target return value +mean_etl_opt <- function(R, constraints, moments, alpha, solver){ + # create a copy of the moments that can be modified + tmp_moments <- moments - # if all(moments$mean == 0) then the user did not specify mean as an objective, - # and we just want to return the target mean return value - if(all(moments$mean == 0)) return(target) - - fmean <- matrix(moments$mean, ncol=1) - - # can't use optimize.portfolio here, this function is called inside - # optimize.portfolio and will throw an error message about nesting too deeply - # Find the maximum return if(!is.null(constraints$max_pos)){ max_ret <- maxret_milp_opt(R=R, constraints=constraints, moments=moments, target=NA, solver=solver) @@ -958,189 +952,301 @@ } max_mean <- as.numeric(-max_ret$out) - # Find the starr at the maximum etl portfolio + # Find the minimum return + tmp_moments$mean <- -1 * moments$mean if(!is.null(constraints$max_pos)){ - ub_etl <- etl_milp_opt(R=R, constraints=constraints, moments=moments, target=max_mean, alpha=alpha, solver=solver) + min_ret <- maxret_milp_opt(R=R, constraints=constraints, moments=tmp_moments, target=NA, solver=solver) } else { - ub_etl <- etl_opt(R=R, constraints=constraints, moments=moments, target=max_mean, alpha=alpha, solver=solver) + min_ret <- maxret_opt(R=R, constraints=constraints, moments=tmp_moments, target=NA, solver=solver) } - ub_weights <- matrix(ub_etl$weights, ncol=1) - ub_mean <- as.numeric(t(ub_weights) %*% fmean) - ub_etl <- as.numeric(ub_etl$out) - # starr at the upper bound - ub_starr <- ub_mean / ub_etl - if(is.infinite(ub_starr)) stop("Inf value for STARR, objective value is 0") + min_mean <- as.numeric(min_ret$out) - # cat("ub_mean", ub_mean, "\n") - # cat("ub_etl", ub_etl, "\n") - # cat("ub_starr", ub_starr, "\n") - - # Find the starr at the minimum etl portfolio + # use optimize() to find the target return value that maximizes sharpe ratio + opt <- try(optimize(f=starr_obj_fun, R=R, constraints=constraints, + solver=solver, moments=moments, alpha=alpha, + lower=min_mean, upper=max_mean, + maximum=TRUE, tol=.Machine$double.eps), + silent=TRUE) + if(inherits(opt, "try-error")){ + stop(paste("Objective function failed with message\n", opt)) + return(NULL) + } + return(opt$maximum) +} + +# Function to calculate the starr ratio. +# Used as the objective function for optimize() +starr_obj_fun <- function(target_return, R, constraints, moments, alpha, solver){ if(!is.null(constraints$max_pos)){ - lb_etl <- etl_milp_opt(R=R, constraints=constraints, moments=moments, target=NA, alpha=alpha, solver=solver) + opt <- etl_milp_opt(R=R, constraints=constraints, moments=moments, + target=target_return, alpha=alpha, solver=solver) } else { - lb_etl <- etl_opt(R=R, constraints=constraints, moments=moments, target=NA, alpha=alpha, solver=solver) + opt <- etl_opt(R=R, constraints=constraints, moments=moments, + target=target_return, alpha=alpha, solver=solver) } - lb_weights <- matrix(lb_etl$weights) - lb_mean <- as.numeric(t(lb_weights) %*% fmean) - lb_etl <- as.numeric(lb_etl$out) - - # starr at the lower bound - lb_starr <- lb_mean / lb_etl - # if(is.infinite(lb_starr)) stop("Inf value for STARR, objective value is 0") - - # set lb_starr equal to 0, should this be a negative number like -1e6? - # the lb_* values will be 0 for a dollar-neutral strategy so we need to reset the values - if(is.na(lb_starr) | is.infinite(lb_starr)) lb_starr <- 0 - - # cat("lb_mean", lb_mean, "\n") - # cat("lb_etl", lb_etl, "\n") - # cat("lb_starr", lb_starr, "\n") - - # want to find the return that maximizes mean / etl - i <- 1 - while((abs(ub_starr - lb_starr) > tol) & (i < maxit)){ - # bisection method to find the maximum mean / etl - - # print(i) - # cat("ub_starr", ub_starr, "\n") - # cat("lb_starr", lb_starr, "\n") - # print("**********") - # Find the starr at the mean return midpoint - new_ret <- (lb_mean + ub_mean) / 2 - if(!is.null(constraints$max_pos)){ - mid <- etl_milp_opt(R=R, constraints=constraints, moments=moments, target=new_ret, alpha=alpha, solver=solver) - } else { - mid <- etl_opt(R=R, constraints=constraints, moments=moments, target=new_ret, alpha=alpha, solver=solver) - } - # print(mid) - mid_weights <- matrix(mid$weights, ncol=1) - mid_mean <- as.numeric(t(mid_weights) %*% fmean) - mid_etl <- as.numeric(mid$out) - mid_starr <- mid_mean / mid_etl - # the mid_* values MIGHT be 0 for a dollar-neutral strategy so we need to reset the values - # if(is.na(mid_starr) | is.infinite(mid_starr)) mid_starr <- 0 - # tmp_starr <- mid_starr - - # cat("mid_mean", mid_mean, "\n") - # cat("mid_etl", mid_etl, "\n") - # cat("mid_starr", mid_starr, "\n") - - if(mid_starr > ub_starr){ - # if mid_starr > ub_starr then mid_starr becomes the new upper bound - ub_mean <- mid_mean - ub_starr <- mid_starr - new_ret <- (lb_mean + ub_mean) / 2 - if(!is.null(constraints$max_pos)){ - mid <- etl_milp_opt(R=R, constraints=constraints, moments=moments, target=new_ret, alpha=alpha, solver=solver) - } else { - mid <- etl_opt(R=R, constraints=constraints, moments=moments, target=new_ret, alpha=alpha, solver=solver) - } - mid_weights <- matrix(mid$weights, ncol=1) - mid_mean <- as.numeric(t(mid_weights) %*% fmean) - mid_etl <- as.numeric(mid$out) - mid_starr <- mid_mean / mid_etl - # the mid_* values MIGHT be 0 for a dollar-neutral strategy so we need to reset the values - # if(is.na(mid_starr) | is.infinite(mid_starr)) mid_starr <- 0 - } else if(mid_starr > lb_starr){ - # if mid_starr > lb_starr then mid_starr becomes the new lower bound - lb_mean <- mid_mean - lb_starr <- mid_starr - new_ret <- (lb_mean + ub_mean) / 2 - if(!is.null(constraints$max_pos)){ - mid <- etl_milp_opt(R=R, constraints=constraints, moments=moments, target=new_ret, alpha=alpha, solver=solver) - } else { - mid <- etl_opt(R=R, constraints=constraints, moments=moments, target=new_ret, alpha=alpha, solver=solver) - } - mid_weights <- matrix(mid$weights, ncol=1) - mid_mean <- as.numeric(t(mid_weights) %*% fmean) - mid_etl <- as.numeric(mid$out) - mid_starr <- mid_mean / mid_etl - # the mid_* values MIGHT be 0 for a dollar-neutral strategy so we need to reset the values - # if(is.na(mid_starr) | is.infinite(mid_starr)) mid_starr <- 0 - } - i <- i + 1 - } - return(new_ret) + weights <- matrix(opt$weights, ncol=1) + opt_mean <- as.numeric(t(weights) %*% matrix(moments$mean, ncol=1)) + opt_etl <- as.numeric(opt$out) + starr <- opt_mean / opt_etl + return(starr) } -max_sr_opt <- function(R, constraints, moments, lambda, target, lambda_hhi, conc_groups, solver="quadprog", tol=.Machine$double.eps^0.5, maxit=50){ - # This function returns the target mean return that maximizes mean / sd (i.e. sharpe ratio) + +# This was my implementation of a binary search for the maximum starr ratio +# target return. Better to use optimize() in R rather than my method. -Ross Bennett +# mean_etl_opt <- function(R, constraints, moments, target, alpha, solver="glpk", tol=.Machine$double.eps^0.5, maxit=50){ +# # This function returns the target mean return that maximizes mean / etl (i.e. starr) +# +# # if all(moments$mean == 0) then the user did not specify mean as an objective, +# # and we just want to return the target mean return value +# if(all(moments$mean == 0)) return(target) +# +# fmean <- matrix(moments$mean, ncol=1) +# +# # can't use optimize.portfolio here, this function is called inside +# # optimize.portfolio and will throw an error message about nesting too deeply +# +# # Find the maximum return +# if(!is.null(constraints$max_pos)){ +# max_ret <- maxret_milp_opt(R=R, constraints=constraints, moments=moments, target=NA, solver=solver) +# } else { +# max_ret <- maxret_opt(R=R, moments=moments, constraints=constraints, target=NA, solver=solver) +# } +# max_mean <- as.numeric(-max_ret$out) +# +# # Find the starr at the maximum etl portfolio +# if(!is.null(constraints$max_pos)){ +# ub_etl <- etl_milp_opt(R=R, constraints=constraints, moments=moments, target=max_mean, alpha=alpha, solver=solver) +# } else { +# ub_etl <- etl_opt(R=R, constraints=constraints, moments=moments, target=max_mean, alpha=alpha, solver=solver) +# } +# ub_weights <- matrix(ub_etl$weights, ncol=1) +# ub_mean <- as.numeric(t(ub_weights) %*% fmean) +# ub_etl <- as.numeric(ub_etl$out) +# # starr at the upper bound +# ub_starr <- ub_mean / ub_etl +# if(is.infinite(ub_starr)) stop("Inf value for STARR, objective value is 0") +# +# # cat("ub_mean", ub_mean, "\n") +# # cat("ub_etl", ub_etl, "\n") +# # cat("ub_starr", ub_starr, "\n") +# +# # Find the starr at the minimum etl portfolio +# if(!is.null(constraints$max_pos)){ +# lb_etl <- etl_milp_opt(R=R, constraints=constraints, moments=moments, target=NA, alpha=alpha, solver=solver) +# } else { +# lb_etl <- etl_opt(R=R, constraints=constraints, moments=moments, target=NA, alpha=alpha, solver=solver) +# } +# lb_weights <- matrix(lb_etl$weights) +# lb_mean <- as.numeric(t(lb_weights) %*% fmean) +# lb_etl <- as.numeric(lb_etl$out) +# +# # starr at the lower bound +# lb_starr <- lb_mean / lb_etl +# # if(is.infinite(lb_starr)) stop("Inf value for STARR, objective value is 0") +# +# # set lb_starr equal to 0, should this be a negative number like -1e6? +# # the lb_* values will be 0 for a dollar-neutral strategy so we need to reset the values +# if(is.na(lb_starr) | is.infinite(lb_starr)) lb_starr <- 0 +# +# # cat("lb_mean", lb_mean, "\n") +# # cat("lb_etl", lb_etl, "\n") +# # cat("lb_starr", lb_starr, "\n") +# +# # want to find the return that maximizes mean / etl +# i <- 1 +# while((abs(ub_starr - lb_starr) > tol) & (i < maxit)){ +# # bisection method to find the maximum mean / etl +# +# # print(i) +# # cat("ub_starr", ub_starr, "\n") +# # cat("lb_starr", lb_starr, "\n") +# # print("**********") +# # Find the starr at the mean return midpoint +# new_ret <- (lb_mean + ub_mean) / 2 +# if(!is.null(constraints$max_pos)){ +# mid <- etl_milp_opt(R=R, constraints=constraints, moments=moments, target=new_ret, alpha=alpha, solver=solver) +# } else { +# mid <- etl_opt(R=R, constraints=constraints, moments=moments, target=new_ret, alpha=alpha, solver=solver) +# } +# # print(mid) +# mid_weights <- matrix(mid$weights, ncol=1) +# mid_mean <- as.numeric(t(mid_weights) %*% fmean) +# mid_etl <- as.numeric(mid$out) +# mid_starr <- mid_mean / mid_etl +# # the mid_* values MIGHT be 0 for a dollar-neutral strategy so we need to reset the values +# # if(is.na(mid_starr) | is.infinite(mid_starr)) mid_starr <- 0 +# # tmp_starr <- mid_starr +# +# # cat("mid_mean", mid_mean, "\n") +# # cat("mid_etl", mid_etl, "\n") +# # cat("mid_starr", mid_starr, "\n") +# +# if(mid_starr > ub_starr){ +# # if mid_starr > ub_starr then mid_starr becomes the new upper bound +# ub_mean <- mid_mean +# ub_starr <- mid_starr +# new_ret <- (lb_mean + ub_mean) / 2 +# if(!is.null(constraints$max_pos)){ +# mid <- etl_milp_opt(R=R, constraints=constraints, moments=moments, target=new_ret, alpha=alpha, solver=solver) +# } else { +# mid <- etl_opt(R=R, constraints=constraints, moments=moments, target=new_ret, alpha=alpha, solver=solver) +# } +# mid_weights <- matrix(mid$weights, ncol=1) +# mid_mean <- as.numeric(t(mid_weights) %*% fmean) +# mid_etl <- as.numeric(mid$out) +# mid_starr <- mid_mean / mid_etl +# # the mid_* values MIGHT be 0 for a dollar-neutral strategy so we need to reset the values +# # if(is.na(mid_starr) | is.infinite(mid_starr)) mid_starr <- 0 +# } else if(mid_starr > lb_starr){ +# # if mid_starr > lb_starr then mid_starr becomes the new lower bound +# lb_mean <- mid_mean +# lb_starr <- mid_starr +# new_ret <- (lb_mean + ub_mean) / 2 +# if(!is.null(constraints$max_pos)){ +# mid <- etl_milp_opt(R=R, constraints=constraints, moments=moments, target=new_ret, alpha=alpha, solver=solver) +# } else { +# mid <- etl_opt(R=R, constraints=constraints, moments=moments, target=new_ret, alpha=alpha, solver=solver) +# } +# mid_weights <- matrix(mid$weights, ncol=1) +# mid_mean <- as.numeric(t(mid_weights) %*% fmean) +# mid_etl <- as.numeric(mid$out) +# mid_starr <- mid_mean / mid_etl +# # the mid_* values MIGHT be 0 for a dollar-neutral strategy so we need to reset the values +# # if(is.na(mid_starr) | is.infinite(mid_starr)) mid_starr <- 0 +# } +# i <- i + 1 +# } +# return(new_ret) +# } + + + +# Function to calculate the sharpe ratio. +# Used as the objective function for optimize() +sharpe_obj_fun <- function(target_return, R, constraints, moments, lambda_hhi=NULL, conc_groups=NULL, solver="quadprog"){ + opt <- gmv_opt(R=R, constraints=constraints, moments=moments, lambda=1, + target=target_return, lambda_hhi=lambda_hhi, + conc_groups=conc_groups, solver=solver) + weights <- opt$weights + opt_mean <- as.numeric(t(weights) %*% matrix(moments$mean, ncol=1)) + opt_sd <- as.numeric(sqrt(t(weights) %*% moments$var %*% weights)) + opt_sr <- opt_mean / opt_sd + return(opt_sr) +} + +# This function uses optimize() to find the target return value that +# results in the maximum sharpe ratio (mean / sd). +# returns the target return value +max_sr_opt <- function(R, constraints, moments, lambda_hhi, conc_groups, solver){ + # create a copy of the moments that can be modified + tmp_moments <- moments - # get the forecast mean from moments - fmean <- matrix(moments$mean, ncol=1) - # Find the maximum return - max_ret <- maxret_opt(R=R, moments=moments, constraints=constraints, target=NA) + max_ret <- maxret_opt(R=R, moments=moments, constraints=constraints, + target=NA, solver="glpk") max_mean <- as.numeric(-max_ret$out) - # Calculate the sr at the maximum mean return portfolio - ub_weights <- matrix(max_ret$weights, ncol=1) - ub_mean <- max_mean - ub_sd <- as.numeric(sqrt(t(ub_weights) %*% moments$var %*% ub_weights)) - # sr at the upper bound - ub_sr <- ub_mean / ub_sd + # Find the minimum return + tmp_moments$mean <- -1 * moments$mean + min_ret <- maxret_opt(R=R, moments=tmp_moments, constraints=constraints, + target=NA, solver="glpk") + min_mean <- as.numeric(min_ret$out) - # Calculate the sr at the miminum var portfolio - tmpmoments <- moments - tmpmoments$mean <- rep(0, length(moments$mean)) - lb_sr <- gmv_opt(R=R, constraints=constraints, moments=tmpmoments, lambda=1, target=NA, lambda_hhi=lambda_hhi, conc_groups=conc_groups, solver=solver) - lb_weights <- matrix(lb_sr$weights) - lb_mean <- as.numeric(t(lb_weights) %*% fmean) - lb_sd <- as.numeric(sqrt(t(lb_weights) %*% moments$var %*% lb_weights)) - # sr at the lower bound - lb_sr <- lb_mean / lb_sd - - # cat("lb_mean:", lb_mean, "\n") - # cat("ub_mean:", ub_mean, "\n") - # print("**********") - - # want to find the return that maximizes mean / sd - i <- 1 - while((abs(ub_sr - lb_sr) > tol) & (i < maxit)){ - # bisection method to find the maximum mean / sd - - # Find the starr at the mean return midpoint - new_ret <- (lb_mean + ub_mean) / 2 - mid <- gmv_opt(R=R, constraints=constraints, moments=tmpmoments, lambda=1, target=new_ret, lambda_hhi=lambda_hhi, conc_groups=conc_groups, solver=solver) - mid_weights <- matrix(mid$weights, ncol=1) - mid_mean <- as.numeric(t(mid_weights) %*% fmean) - mid_sd <- as.numeric(sqrt(t(mid_weights) %*% moments$var %*% mid_weights)) - mid_sr <- mid_mean / mid_sd - # tmp_sr <- mid_sr - - # print(i) - # cat("new_ret:", new_ret, "\n") - # cat("mid_sr:", mid_sr, "\n") - # print("**********") - - if(mid_sr > ub_sr){ - # if mid_sr > ub_sr then mid_sr becomes the new upper bound - ub_mean <- mid_mean - ub_sr <- mid_sr - new_ret <- (lb_mean + ub_mean) / 2 - mid <- gmv_opt(R=R, constraints=constraints, moments=tmpmoments, lambda=1, target=new_ret, lambda_hhi=lambda_hhi, conc_groups=conc_groups, solver=solver) - mid_weights <- matrix(mid$weights, ncol=1) - mid_mean <- as.numeric(t(mid_weights) %*% fmean) - mid_sd <- as.numeric(sqrt(t(mid_weights) %*% moments$var %*% mid_weights)) - mid_sr <- mid_mean / mid_sd - } else if(mid_sr > lb_sr){ - # if mid_sr > lb_sr then mid_sr becomes the new lower bound - lb_mean <- mid_mean - lb_sr <- mid_sr - new_ret <- (lb_mean + ub_mean) / 2 - mid <- gmv_opt(R=R, constraints=constraints, moments=tmpmoments, lambda=1, target=new_ret, lambda_hhi=lambda_hhi, conc_groups=conc_groups, solver=solver) - mid_weights <- matrix(mid$weights, ncol=1) - mid_mean <- as.numeric(t(mid_weights) %*% fmean) - mid_sd <- as.numeric(sqrt(t(mid_weights) %*% moments$var %*% mid_weights)) - mid_sr <- mid_mean / mid_sd - } - i <- i + 1 + # use optimize() to find the target return value that maximizes sharpe ratio + opt <- try(optimize(f=sharpe_obj_fun, R=R, constraints=constraints, + solver=solver, lambda_hhi=lambda_hhi, + conc_groups=conc_groups, moments=moments, + lower=min_mean, upper=max_mean, + maximum=TRUE, tol=.Machine$double.eps), + silent=TRUE) + if(inherits(opt, "try-error")){ + stop(paste("Objective function failed with message\n", opt)) + return(NULL) } - return(new_ret) + return(opt$maximum) } +# This was my implementation of a binary search for the maximum sharpe ratio +# target return. Better to use optimize() in R rather than my method. -Ross Bennett +# max_sr_opt <- function(R, constraints, moments, lambda, target, lambda_hhi, conc_groups, solver="quadprog", tol=.Machine$double.eps^0.5, maxit=50){ +# # This function returns the target mean return that maximizes mean / sd (i.e. sharpe ratio) +# +# # get the forecast mean from moments +# fmean <- matrix(moments$mean, ncol=1) +# +# # Find the maximum return +# max_ret <- maxret_opt(R=R, moments=moments, constraints=constraints, target=NA) +# max_mean <- as.numeric(-max_ret$out) +# +# # Calculate the sr at the maximum mean return portfolio +# ub_weights <- matrix(max_ret$weights, ncol=1) +# ub_mean <- max_mean +# ub_sd <- as.numeric(sqrt(t(ub_weights) %*% moments$var %*% ub_weights)) +# # sr at the upper bound +# ub_sr <- ub_mean / ub_sd +# +# # Calculate the sr at the miminum var portfolio +# tmpmoments <- moments +# tmpmoments$mean <- rep(0, length(moments$mean)) +# lb_sr <- gmv_opt(R=R, constraints=constraints, moments=tmpmoments, lambda=1, target=NA, lambda_hhi=lambda_hhi, conc_groups=conc_groups, solver=solver) +# lb_weights <- matrix(lb_sr$weights) +# lb_mean <- as.numeric(t(lb_weights) %*% fmean) +# lb_sd <- as.numeric(sqrt(t(lb_weights) %*% moments$var %*% lb_weights)) +# # sr at the lower bound +# lb_sr <- lb_mean / lb_sd +# +# # cat("lb_mean:", lb_mean, "\n") +# # cat("ub_mean:", ub_mean, "\n") +# # print("**********") +# +# # want to find the return that maximizes mean / sd +# i <- 1 +# while((abs(ub_sr - lb_sr) > tol) & (i < maxit)){ +# # bisection method to find the maximum mean / sd +# +# # Find the starr at the mean return midpoint +# new_ret <- (lb_mean + ub_mean) / 2 +# mid <- gmv_opt(R=R, constraints=constraints, moments=tmpmoments, lambda=1, target=new_ret, lambda_hhi=lambda_hhi, conc_groups=conc_groups, solver=solver) +# mid_weights <- matrix(mid$weights, ncol=1) +# mid_mean <- as.numeric(t(mid_weights) %*% fmean) +# mid_sd <- as.numeric(sqrt(t(mid_weights) %*% moments$var %*% mid_weights)) +# mid_sr <- mid_mean / mid_sd +# # tmp_sr <- mid_sr +# +# # print(i) +# # cat("new_ret:", new_ret, "\n") +# # cat("mid_sr:", mid_sr, "\n") +# # print("**********") +# +# if(mid_sr > ub_sr){ +# # if mid_sr > ub_sr then mid_sr becomes the new upper bound +# ub_mean <- mid_mean +# ub_sr <- mid_sr +# new_ret <- (lb_mean + ub_mean) / 2 +# mid <- gmv_opt(R=R, constraints=constraints, moments=tmpmoments, lambda=1, target=new_ret, lambda_hhi=lambda_hhi, conc_groups=conc_groups, solver=solver) +# mid_weights <- matrix(mid$weights, ncol=1) +# mid_mean <- as.numeric(t(mid_weights) %*% fmean) +# mid_sd <- as.numeric(sqrt(t(mid_weights) %*% moments$var %*% mid_weights)) +# mid_sr <- mid_mean / mid_sd +# } else if(mid_sr > lb_sr){ +# # if mid_sr > lb_sr then mid_sr becomes the new lower bound +# lb_mean <- mid_mean +# lb_sr <- mid_sr +# new_ret <- (lb_mean + ub_mean) / 2 +# mid <- gmv_opt(R=R, constraints=constraints, moments=tmpmoments, lambda=1, target=new_ret, lambda_hhi=lambda_hhi, conc_groups=conc_groups, solver=solver) +# mid_weights <- matrix(mid$weights, ncol=1) +# mid_mean <- as.numeric(t(mid_weights) %*% fmean) +# mid_sd <- as.numeric(sqrt(t(mid_weights) %*% moments$var %*% mid_weights)) +# mid_sr <- mid_mean / mid_sd +# } +# i <- i + 1 +# } +# return(new_ret) +# } + + ############################################################################### # R (http://r-project.org/) Numeric Methods for Optimization of Portfolios # Modified: pkg/PortfolioAnalytics/R/optimize.portfolio.R =================================================================== --- pkg/PortfolioAnalytics/R/optimize.portfolio.R 2014-02-20 22:56:08 UTC (rev 3320) +++ pkg/PortfolioAnalytics/R/optimize.portfolio.R 2014-02-20 23:02:12 UTC (rev 3321) @@ -857,7 +857,7 @@ # if(hasArg(ef)) ef=match.call(expand.dots=TRUE)$ef else ef=FALSE if(hasArg(maxSR)) maxSR=match.call(expand.dots=TRUE)$maxSR else maxSR=FALSE if(maxSR){ - target <- max_sr_opt(R=R, constraints=constraints, moments=moments, lambda=lambda, target=target, lambda_hhi=lambda_hhi, conc_groups=conc_groups, solver=solver) + target <- max_sr_opt(R=R, constraints=constraints, moments=moments, lambda_hhi=lambda_hhi, conc_groups=conc_groups, solver=solver) # need to set moments$mean=0 here because quadratic utility and target return is sensitive to returning no solution tmp_moments_mean <- moments$mean moments$mean <- rep(0, length(moments$mean)) @@ -918,7 +918,7 @@ # Minimize sample ETL/ES/CVaR if CVaR, ETL, or ES is specified as an objective if(length(moments) == 2 & all(moments$mean != 0) & ef==FALSE & maxSTARR){ # This is called by meanetl.efficient.frontier and we do not want that for efficient frontiers, need to have ef==FALSE - target <- mean_etl_opt(R=R, constraints=constraints, moments=moments, target=target, alpha=alpha, solver=solver) + target <- mean_etl_opt(R=R, constraints=constraints, moments=moments, alpha=alpha, solver=solver) meanetl <- TRUE } if(!is.null(constraints$max_pos)) { Added: pkg/PortfolioAnalytics/sandbox/testing_max_starr_sharpe.R =================================================================== --- pkg/PortfolioAnalytics/sandbox/testing_max_starr_sharpe.R (rev 0) +++ pkg/PortfolioAnalytics/sandbox/testing_max_starr_sharpe.R 2014-02-20 23:02:12 UTC (rev 3321) @@ -0,0 +1,40 @@ +library(PortfolioAnalytics) + +# Examples of passing a list portfolio objects to optimize.portfolio and +# optimize.portfolio.rebalancing + +data(edhec) +R <- edhec[, 1:4] +funds <- colnames(R) + +# Construct initial portfolio +init.portf <- portfolio.spec(assets=funds) +init.portf <- add.constraint(portfolio=init.portf, type="weight_sum", + min_sum=0.99, max_sum=1.01) +init.portf <- add.constraint(portfolio=init.portf, type="long_only") + +# Maximize sharpe ratio +sharpe.portf <- add.objective(portfolio=init.portf, type="risk", name="StdDev") +sharpe.portf <- add.objective(portfolio=sharpe.portf, type="return", name="mean") + +# Optimization to maximize Sharpe Ratio +max_sharpe_opt <- optimize.portfolio(R=R, portfolio=sharpe.portf, optimize_method="ROI", maxSR=TRUE) +max_sharpe_opt + +# calculate sharpe ratio from efficient frontier and optimization +ef1 <- create.EfficientFrontier(R=R, portfolio=sharpe.portf, type="mean-sd", n.portfolios=100) +max(ef1$frontier[,"mean"] / ef1$frontier[,"StdDev"]) +max_sharpe_opt$objective_measures$mean / max_sharpe_opt$objective_measures$StdDev + +# Maximize starr +starr.portf <- add.objective(portfolio=init.portf, type="risk", name="ES") +starr.portf <- add.objective(portfolio=starr.portf, type="return", name="mean") + +max_starr_opt <- optimize.portfolio(R=R, portfolio=starr.portf, optimize_method="ROI", maxSTARR=TRUE) +max_starr_opt + +# calculate starr ratio from efficient frontier and optimization +ef2 <- create.EfficientFrontier(R=R, portfolio=starr.portf, type="mean-ES", n.portfolios=100) +max(ef2$frontier[,"mean"] / ef2$frontier[,"ES"]) +max_starr_opt$objective_measures$mean / max_starr_opt$objective_measures$ES + From noreply at r-forge.r-project.org Fri Feb 21 03:44:51 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 21 Feb 2014 03:44:51 +0100 (CET) Subject: [Returnanalytics-commits] r3322 - pkg/FactorAnalytics/R Message-ID: <20140221024451.B6118186943@r-forge.r-project.org> Author: efmrforge Date: 2014-02-21 03:44:50 +0100 (Fri, 21 Feb 2014) New Revision: 3322 Removed: pkg/FactorAnalytics/R/.Rhistory Log: Removed .Rhistory Deleted: pkg/FactorAnalytics/R/.Rhistory =================================================================== --- pkg/FactorAnalytics/R/.Rhistory 2014-02-20 23:02:12 UTC (rev 3321) +++ pkg/FactorAnalytics/R/.Rhistory 2014-02-21 02:44:50 UTC (rev 3322) @@ -1,512 +0,0 @@ -nrow=6) -gplot(t(adj.mat),gmode="digraph",label=c(1,2,3,4,5,6),vertex.cex=2, -arrowhead.cex = 1) -gplot(t(adj.mat1),gmode="digraph",label=c(1,2,3,4,5,6),vertex.cex=2, -arrowhead.cex = 1) -gplot(t(adj.mat1),gmode="digraph",label=c(1,2,3,4,5,6),vertex.cex=2, -arrowhead.cex = 1) -gplot(t(adj.mat),gmode="digraph",label=c(1,2,3,4,5,6),vertex.cex=2, -arrowhead.cex = 1) -rm(list=ls()) -library(factorAnalytics) -library(fEcofin) -ts.berndt<-xts(berndtInvest[,-1],as.Date(berndtInvest[,1])) -data(stat.fm.data) -View(sfm.dat) -install.packages("~/R-project/returnanalytics/pkg/FactorAnalytics/sandbox/fEcofin_2100.77.zip-UWunsafe", repos = NULL) -install.packages("~/R-project/returnanalytics/pkg/FactorAnalytics/sandbox/fEcofin_2100.77.zip", repos = NULL) -library(fEcofin) -? fEconfin -fEconfin -help(pakcage=fEconfin) -help(package=fEconfin) -help(package=fEcofin) -data(berndtInvest) -ts.berndt<-xts(berndtInvest[,-1],as.Date(berndtInvest[,1])) -berndt<-ts.berndt['1978/1987'] -returns<-berndt[,c(-10,-17)] -tickers <- names(returns) -num.tickers <- length(tickers) -dates <- index(returns) -num.dates <- length(dates) -sector<-c("OTHER","OTHER","OIL","TECH","TECH","OIL","OTHER","OTHER", -"TECH","OIL","OIL","OTHER","TECH","OIL","OTHER") -stacked.returns <- data.frame( -DATE=rep(dates,num.tickers), -TICKER=rep(tickers,each=num.dates), -RETURN=c(coredata(returns)), -SECTOR=rep(sector,each=num.dates), -stringsAsFactors=FALSE) -head(stacked.returns) -barra <- fitFundamentalFactorModel(data=stacked.returns,exposure.names="SECTOR", -datevar="DATE",returnsvar="RETURN", -assetvar="TICKER",wls=TRUE) -head(barra$factor.returns) -barra$beta -barra.cov <- factorModelCovariance(barra$beta, barra$factor.cov$cov, barra$resid.variance) -barra.cor <- cov2cor(barra.cov) -round(barra.cor,2) -View(stacked.returns) -returns = berndtInvest[,-c(1,11,18)] -n.stocks = ncol(returns) -tech.dum = oil.dum = other.dum = matrix(0,n.stocks,1) -tech.dum[c(4,5,9,13),] = 1 -oil.dum[c(3,6,10,11,14),] = 1 -other.dum = 1 - tech.dum - oil.dum -B = cbind(tech.dum,oil.dum,other.dum) -dimnames(B) = list(colnames(returns),c("TECH","OIL","OTHER")) -B -returns = t(returns) -F.hat = solve(crossprod(B))%*%t(B)%*%returns -E.hat = returns - B%*%F.hat -diagD.hat = apply(E.hat,1,var) -Dinv.hat = diag(diagD.hat^(-1)) -H = solve(t(B)%*%Dinv.hat%*%B)%*%t(B)%*%Dinv.hat -round(H[,1:8],5) -apply(H,1,sum) -F.hat = H%*%returns -E.hat = returns - B%*%F.hat -diagD.hat = apply(E.hat,1,var) -F.hat = t(F.hat) -F.hat -round(H[,1:8],5) -H -B -returns -View(berndtInvest) -H -names(barra) -barra$factor.returns -H -F.hat -head(barra$factor.returns) -head(F.hat) -oil.f.ret <- barra$returns[,1] -oth.f.ret <- barra$returns[,1]+barra$returns[,2] -tech.f.ret <- barra$returns[,1]+barra$returns[,3] -head(oil.f.ret) -oil.f.ret <- barra$factor.returns[,1] -tech.f.ret <- barra$factor.returns[,1]+ barra$factor.returns[,3] -oth.f.ret <- barra$factor.returns[,1]+barra$factor.returns[,2] -head(oil.f.ret) -head(F.hat) -head(F.hat)[,2] -head(barra$factor.returns) -head(F.hat) -head(cbind(tech.f.ret,oil.f.ret,oth.f.ret)) -tickers -cbind(tickers,sector) -barra$beta -names(barra) -? fitFundamentalFactorModel -barra.cov2 <- barra$factor.cov -barra.cov2 -barra.cov2 <- barra$returns.cov -barra.cov2 -barra.cor2 <- cov2cor(barra.cov2) -barra.cor2 <- cov2cor(barra.cov2$cov) -cov.ind = B%*%var(F.hat)%*%t(B) + diag(diagD.hat) -sd = sqrt(diag(cov.ind)) -cor.ind = cov.ind/outer(sd,sd) -cor.samp <- cor(t(returns)) -View(cor.samp) -View(barra.cor2) -data(berndtInvest) -ts.berndt<-xts(berndtInvest[,-1],as.Date(berndtInvest[,1])) -berndt<-ts.berndt['1978/1987'] -returns<-berndt[,c(-10,-17)] -tickers <- names(returns) -num.tickers <- length(tickers) -dates <- index(returns) -num.dates <- length(dates) -sector<-c("OTHER","OTHER","OIL","TECH","TECH","OIL","OTHER","OTHER", -"TECH","OIL","OIL","OTHER","TECH","OIL","OTHER") -stacked.returns <- data.frame( -DATE=rep(dates,num.tickers), -TICKER=rep(tickers,each=num.dates), -RETURN=c(coredata(returns)), -SECTOR=rep(sector,each=num.dates), -stringsAsFactors=FALSE) -head(stacked.returns) -data=stacked.returns -exposure.names="SECTOR" -datevar="DATE", -datevar="DATE" -returnsvar="RETURN" -assetvar="TICKER" -wls=TRUE -full.resid.cov=FALSE -assets = unique(data[[assetvar]]) -timedates = as.Date(unique(data[[datevar]])) -data[[datevar]] <- as.Date(data[[datevar]]) -if (length(timedates) < 2) -stop("At least two time points, t and t-1, are needed for fitting the factor model.") -if (!is(exposure.names, "vector") || !is.character(exposure.names)) -stop("exposure argument invalid---must be character vector.") -if (!is(assets, "vector") || !is.character(assets)) -stop("assets argument invalid---must be character vector.") -wls <- as.logical(wls) -full.resid.cov <- as.logical(full.resid.cov) -robust.scale = FALSE -standardized.factor.exposure = FALSE -numTimePoints <- length(timedates) -numExposures <- length(exposure.names) -numAssets <- length(assets) -# check if exposure.names are numeric, if not, create exposures. factors by dummy variables -which.numeric <- sapply(data[, exposure.names, drop = FALSE],is.numeric) -exposures.numeric <- exposure.names[which.numeric] -# industry factor model -exposures.factor <- exposure.names[!which.numeric] -if (length(exposures.factor) > 1) { -stop("Only one nonnumeric variable can be used at this time.") -} -exposures.factor -regression.formula <- paste("~", paste(exposure.names, collapse = "+")) -if (length(exposures.factor)) { -regression.formula <- paste(regression.formula, "- 1") -data[, exposures.factor] <- as.factor(data[,exposures.factor]) -exposuresToRecode <- names(data[, exposure.names, drop = FALSE])[!which.numeric] -contrasts.list <- lapply(seq(length(exposuresToRecode)), -function(i) function(n, m) contr.treatment(n, contrasts = FALSE)) -names(contrasts.list) <- exposuresToRecode -} else { -contrasts.list <- NULL -} -# turn characters into formula -regression.formula <- eval(parse(text = paste(returnsvar,regression.formula))) -# RETURN ~ BOOK2MARKET -regression.formula -wls.classic <- function(xdf, modelterms, conlist, w) { -assign("w", w, pos = 1) -model <- try(lm(formula = modelterms, data = xdf, contrasts = conlist, -weights = w, singular.ok = FALSE)) -if (is(model, "Error")) { -mess <- geterrmessage() -nn <- regexpr("computed fit is singular", mess) -if (nn > 0) { -cat("At time:", substring(mess, nn), "\n") -model <- lm(formula = modelterms, data = xdf, -contrasts = conlist, weights = w) -} -else stop(mess) -} -} -wls.classic <- function(xdf, modelterms, conlist, w) { -assign("w", w, pos = 1) -model <- try(lm(formula = modelterms, data = xdf, contrasts = conlist, -weights = w, singular.ok = FALSE)) -if (is(model, "Error")) { -mess <- geterrmessage() -nn <- regexpr("computed fit is singular", mess) -if (nn > 0) { -cat("At time:", substring(mess, nn), "\n") -model <- lm(formula = modelterms, data = xdf, -contrasts = conlist, weights = w) -} -else stop(mess) -} -tstat <- rep(NA, length(model$coef)) -tstat[!is.na(model$coef)] <- summary(model, cor = FALSE)$coef[,3] -alphaord <- order(names(model$coef)) -c(length(model$coef), model$coef[alphaord], tstat[alphaord], -model$resid) -} -resids <- by(data = data, INDICES = as.numeric(data[[datevar]]), -FUN = function(xdf, modelterms, conlist) { -lm(formula = modelterms, data = xdf, contrasts = conlist, -singular.ok = TRUE)$resid -}, -modelterms = regression.formula, conlist = contrasts.list) -resids <- apply(resids, 1, unlist) -weights <- if (covariance == "robust") -apply(resids, 1, scaleTau2)^2 -else apply(resids, 1, var) -FE.hat <- by(data = data, INDICES = as.numeric(data[[datevar]]), -FUN = wls.classic, modelterms = regression.formula, -conlist = contrasts.list, w = weights) -covariance = "classic" -wls = TRUE -regression = "classic" -if (!wls) { -if (regression == "robust") { -# ols.robust -FE.hat <- by(data = data, INDICES = as.numeric(data[[datevar]]), -FUN = ols.robust, modelterms = regression.formula, -conlist = contrasts.list) -} else { -# ols.classic -FE.hat <- by(data = data, INDICES = as.numeric(data[[datevar]]), -FUN = ols.classic, modelterms = regression.formula, -conlist = contrasts.list) -} -} else { -if (regression == "robust") { -# wls.robust -resids <- by(data = data, INDICES = as.numeric(data[[datevar]]), -FUN = function(xdf, modelterms, conlist) { -lmRob(modelterms, data = xdf, contrasts = conlist, -control = lmRob.control(mxr = 200, mxf = 200, -mxs = 200))$resid -}, modelterms = regression.formula, conlist = contrasts.list) -resids <- apply(resids, 1, unlist) -weights <- if (covariance == "robust") -apply(resids, 1, scaleTau2)^2 -else apply(resids, 1, var) -FE.hat <- by(data = data, INDICES = as.numeric(data[[datevar]]), -FUN = wls.robust, modelterms = regression.formula, -conlist = contrasts.list, w = weights) -} -else { -# wls.classic -resids <- by(data = data, INDICES = as.numeric(data[[datevar]]), -FUN = function(xdf, modelterms, conlist) { -lm(formula = modelterms, data = xdf, contrasts = conlist, -singular.ok = TRUE)$resid -}, -modelterms = regression.formula, conlist = contrasts.list) -resids <- apply(resids, 1, unlist) -weights <- if (covariance == "robust") -apply(resids, 1, scaleTau2)^2 -else apply(resids, 1, var) -FE.hat <- by(data = data, INDICES = as.numeric(data[[datevar]]), -FUN = wls.classic, modelterms = regression.formula, -conlist = contrasts.list, w = weights) -} -} -FE.hat -FE.hat[1] -FE.hat[[1]] -(length(exposures.factor)) -exposures.factor -length(levels(data[,exposures.factor])) -(length(exposures.factor)>0) -if (length(exposures.factor)>0) { -numCoefs <- length(exposures.numeric) + length(levels(data[,exposures.factor])) -ncols <- 1 + 2 * numCoefs + numAssets -fnames <- c(exposures.numeric, paste(exposures.factor, -levels(data[, exposures.factor]), sep = "")) -cnames <- c("numCoefs", fnames, paste("t", fnames, sep = "."), -assets) -} else { -numCoefs <- 1 + length(exposures.numeric) -ncols <- 1 + 2 * numCoefs + numAssets -cnames <- c("numCoefs", "(Intercept)", exposures.numeric, -paste("t", c("(Intercept)", exposures.numeric), sep = "."), -assets) -} -FE.hat.mat <- matrix(NA, ncol = ncols, nrow = numTimePoints, -dimnames = list(as.character(timedates), cnames)) -for (i in 1:length(FE.hat)) { -names(FE.hat[[i]])[1] <- "numCoefs" -nc <- FE.hat[[i]][1] -names(FE.hat[[i]])[(2 + nc):(1 + 2 * nc)] <- paste("t", -names(FE.hat[[i]])[2:(1 + nc)], sep = ".") -if (length(FE.hat[[i]]) != (1 + 2 * nc + numAssets)) -stop(paste("bad count in row", i, "of FE.hat")) -names(FE.hat[[i]])[(2 + 2 * nc):(1 + 2 * nc + numAssets)] <- assets -idx <- match(names(FE.hat[[i]]), colnames(FE.hat.mat)) -FE.hat.mat[i, idx] <- FE.hat[[i]] -} -coefs.names <- colnames(FE.hat.mat)[2:(1 + numCoefs)] -# estimated factors returns ordered by time -f.hat <- xts(x = FE.hat.mat[, 2:(1 + numCoefs)], order.by = timedates) -# check for outlier -gomat <- apply(coredata(f.hat), 2, function(x) abs(x - median(x, -na.rm = TRUE)) > 4 * mad(x, na.rm = TRUE)) -if (any(gomat, na.rm = TRUE) ) { -cat("\n\n*** Possible outliers found in the factor returns:\n\n") -for (i in which(apply(gomat, 1, any, na.rm = TRUE))) print(f.hat[i, -gomat[i, ], drop = FALSE]) -} -tstats <- xts(x = FE.hat.mat[, (2 + nc):(1 + 2 * nc)], order.by = timedates) -# residuals for every asset ordered by time -resids <- xts(x = FE.hat.mat[, (2 + 2 * numCoefs):(1 + 2 * -numCoefs + numAssets)], order.by = timedates) -Cov.factors <- covClassic(coredata(f.hat), distance = FALSE,na.action = na.omit) -resid.vars <- apply(coredata(resids), 2, var, na.rm = TRUE) -D.hat <- if (full.resid.cov) { -covClassic(coredata(resids), distance = FALSE, na.action = na.omit) -} else { diag(resid.vars) } -B.final <- matrix(0, nrow = numAssets, ncol = numCoefs) -colnames <- coefs.names -B.final -B.final[, match("(Intercept)", colnames, 0)] -B.final[, match("(Intercept)", colnames, 0)] <- 1 -B.final -numeric.columns <- match(exposures.numeric, colnames, 0) -# only take the latest beta to compute FM covariance -B.final[, numeric.columns] <- as.matrix(data[ (data[[datevar]] == timedates[numTimePoints]), exposures.numeric]) -rownames(B.final) = assets -colnames(B.final) = colnames(f.hat) -B.final -(length(exposures.factor)) -if (length(exposures.factor)>0) { -B.final[, grep(exposures.factor, x = colnames)][cbind(seq(numAssets), -(data[ data[[datevar]] == timedates[numTimePoints], -exposures.factor]))] <- 1 -} -B.final -cov.returns <- B.final %*% Cov.factors$cov %*% t(B.final) + -if (full.resid.cov) { D.hat$cov -} else { D.hat } -mean.cov.returns = tapply(data[[returnsvar]],data[[assetvar]], mean) -Cov.returns <- list(cov = cov.returns, mean=mean.cov.returns, eigenvalues = eigen(cov.returns, -only.values = TRUE, symmetric = TRUE)$values) -# report residual covaraince if full.resid.cov is true. -if (full.resid.cov) { -Cov.resids <- D.hat -} -else { -Cov.resids <- diag(resid.vars) -} -f.hat -head(barra$factor.returns) -barra <- fitFundamentalFactorModel(data=stacked.returns,exposure.names="SECTOR", -datevar="DATE",returnsvar="RETURN", -assetvar="TICKER",wls=TRUE,full.resid.cov=FALSE) -head(barra$factor.returns) -head(f.hat) -(!(length(exposures.factor)>0)) -setwd("C:/Users/Yi-An Chen/Documents/R-project/returnanalytics/pkg/FactorAnalytics/R") -source(fitFundamentalFactorModel) -source("fitFundamentalFactorModel.r") -barra <- fitFundamentalFactorModel(data=stacked.returns,exposure.names="SECTOR", -datevar="DATE",returnsvar="RETURN", -assetvar="TICKER",wls=TRUE,full.resid.cov=FALSE) -names(barra) -head(barra$factor.returns) -barra$beta -data(berndtInvest) -ts.berndt<-xts(berndtInvest[,-1],as.Date(berndtInvest[,1])) -berndt<-ts.berndt['1978/1987'] -returns<-berndt[,c(-10,-17)] -tickers <- names(returns) -num.tickers <- length(tickers) -dates <- index(returns) -num.dates <- length(dates) -sector<-c("OTHER","OTHER","OIL","TECH","TECH","OIL","OTHER","OTHER", -"TECH","OIL","OIL","OTHER","TECH","OIL","OTHER") -stacked.returns <- data.frame( -DATE=rep(dates,num.tickers), -TICKER=rep(tickers,each=num.dates), -RETURN=c(coredata(returns)), -SECTOR=rep(sector,each=num.dates), -stringsAsFactors=FALSE) -head(stacked.returns) -setwd("C:/Users/Yi-An Chen/Documents/R-project/returnanalytics/pkg/FactorAnalytics/R") -barra <- fitFundamentalFactorModel(data=stacked.returns,exposure.names="SECTOR", -datevar="DATE",returnsvar="RETURN", -assetvar="TICKER",wls=TRUE,full.resid.cov=FALSE) -names(barra) -head(barra$factor.returns) -setwd("C:/Users/Yi-An Chen/Documents/R-project/returnanalytics/pkg/FactorAnalytics/R") -source("fitFundamentalFactorModel.r") -barra <- fitFundamentalFactorModel(data=stacked.returns,exposure.names="SECTOR", -datevar="DATE",returnsvar="RETURN", -assetvar="TICKER",wls=TRUE,full.resid.cov=FALSE) -names(barra) -head(barra$factor.returns) -barra$beta -barra.cov <- factorModelCovariance(barra$beta, barra$factor.cov$cov, barra$resid.variance) -barra.cor <- cov2cor(barra.cov) -round(barra.cor,2) -returns = berndtInvest[,-c(1,11,18)] -n.stocks = ncol(returns) -tech.dum = oil.dum = other.dum = matrix(0,n.stocks,1) -tech.dum[c(4,5,9,13),] = 1 -oil.dum[c(3,6,10,11,14),] = 1 -other.dum = 1 - tech.dum - oil.dum -B = cbind(tech.dum,oil.dum,other.dum) -dimnames(B) = list(colnames(returns),c("TECH","OIL","OTHER")) -B -returns = t(returns) -barra_ols = lm(returns ~ -1 + B) -sbarra_ols = summary(barra_ols) -e.hat = resid(barra_ols) -e.var = apply(e.hat,1,var) -e.var.inv = e.var^-1 -barra_fgls = lm(returns ~ -1 + B, weights = e.var.inv) -sbarra_fgls = summary(barra_fgls) -f.hat = coef(barra_fgls) -f.hat -e.hat_fgls = resid(barra_fgls) -e.var_fgls = apply(e.hat_fgls,1,var) -cov.ind.lm = B %*% var(t(f.hat)) %*% t(B) + diag(e.var_fgls) -all.equal(cov.ind,cov.ind.lm) -cor.ind.lm <- cov2cor(cov.ind.lm) -round(cor.ind.lm,2) -cov.ind.lm = B %*% var(t(f.hat)) %*% t(B) + diag(e.var_fgls) -all.equal(cov.ind,cov.ind.lm) -F.hat = solve(crossprod(B))%*%t(B)%*%returns -# compute N x T matrix of industry factor model residuals -E.hat = returns - B%*%F.hat -# compute residual variances from time series of errors -diagD.hat = apply(E.hat,1,var) -Dinv.hat = diag(diagD.hat^(-1)) -# multivariate FGLS regression to estimate K x T matrix of factor returns -H = solve(t(B)%*%Dinv.hat%*%B)%*%t(B)%*%Dinv.hat -round(H[,1:8],5) -# note: rows of H sum to one -apply(H,1,sum) -# create factor mimicking portfolios -F.hat = H%*%returns -E.hat = returns - B%*%F.hat -diagD.hat = apply(E.hat,1,var) -F.hat = t(F.hat) -all.equal(cov.ind,cov.ind.lm) -cov.ind = B%*%var(F.hat)%*%t(B) + diag(diagD.hat) -sd = sqrt(diag(cov.ind)) -cor.ind = cov.ind/outer(sd,sd) -cor.samp <- cor(t(returns)) -all.equal(cov.ind,cov.ind.lm) -cor.ind.lm <- cov2cor(cov.ind.lm) -round(cor.ind.lm,2) -barra_ols = lm(returns ~ -1 + B) -sbarra_ols = summary(barra_ols) -e.hat = resid(barra_ols) -e.var = apply(e.hat,1,var) -# e.var.inv = e.var^-1 -e.var.inv = e.var -barra_fgls = lm(returns ~ -1 + B, weights = e.var.inv) -sbarra_fgls = summary(barra_fgls) -f.hat = coef(barra_fgls) -e.hat_fgls = resid(barra_fgls) -e.var_fgls = apply(e.hat_fgls,1,var) -cov.ind.lm = B %*% var(t(f.hat)) %*% t(B) + diag(e.var_fgls) -all.equal(cov.ind,cov.ind.lm) -barra.cov <- factorModelCovariance(barra$beta, barra$factor.cov$cov, barra$resid.variance) -all.equal(cov.ind.lm,barra.cov) -? lm -setwd("C:/Users/Yi-An Chen/Documents/R-project/returnanalytics/pkg/FactorAnalytics/R") -source("fitFundamentalFactorModel.r") -barra <- fitFundamentalFactorModel(data=stacked.returns,exposure.names="SECTOR", -datevar="DATE",returnsvar="RETURN", -assetvar="TICKER",wls=TRUE,full.resid.cov=FALSE) -head(barra$factor.returns) -barra.cov <- factorModelCovariance(barra$beta, barra$factor.cov$cov, barra$resid.variance) -barra.cor <- cov2cor(barra.cov) -round(barra.cor,2) -barra_ols = lm(returns ~ -1 + B) -sbarra_ols = summary(barra_ols) -e.hat = resid(barra_ols) -e.var = apply(e.hat,1,var) -e.var.inv = e.var^-1 -barra_fgls = lm(returns ~ -1 + B, weights = e.var.inv) -sbarra_fgls = summary(barra_fgls) -f.hat = coef(barra_fgls) -e.hat_fgls = resid(barra_fgls) -e.var_fgls = apply(e.hat_fgls,1,var) -cov.ind.lm = B %*% var(t(f.hat)) %*% t(B) + diag(e.var_fgls) -all.equal(cov.ind,cov.ind.lm) -cor.ind.lm <- cov2cor(cov.ind.lm) -round(cor.ind.lm,2) -all.equal(barra.cov,cov.ind.lm) -barra.cov2 <- barra$returns.cov -barra.cor2 <- cov2cor(barra.cov2$cov) -all.equal(barra.cov2,cov.ind.lm) -barra.cov2 -barra.cov2$cov -barra.cor2 <- cov2cor(barra.cov2$cov) -barra.cov2 <- barra$returns.cov$cov -barra.cor2 <- cov2cor(barra.cov2) -all.equal(barra.cov2,cov.ind.lm) From noreply at r-forge.r-project.org Fri Feb 21 03:48:40 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 21 Feb 2014 03:48:40 +0100 (CET) Subject: [Returnanalytics-commits] r3323 - pkg/FactorAnalytics/data Message-ID: <20140221024840.608301869DC@r-forge.r-project.org> Author: efmrforge Date: 2014-02-21 03:48:39 +0100 (Fri, 21 Feb 2014) New Revision: 3323 Removed: pkg/FactorAnalytics/data/.Rhistory Log: Removed .Rhistory Deleted: pkg/FactorAnalytics/data/.Rhistory =================================================================== --- pkg/FactorAnalytics/data/.Rhistory 2014-02-21 02:44:50 UTC (rev 3322) +++ pkg/FactorAnalytics/data/.Rhistory 2014-02-21 02:48:39 UTC (rev 3323) @@ -1,512 +0,0 @@ -eigenvector <- eigen(cov(data))$vectors -eigenvector -u <- 0.2 -chol <- cbind(c(1,p,q,r),c(0,1,s,t),c(0,0,1,u),c(0,0,0,1)) -covvar <- chol%*%t(chol) -covvar -eigenvector <- eigen(cov(data))$vectors -eigenvector -library(corpcor) -install.packages("corpcor") -install.packages("corpcor") -library(corpcor) -? make.positive.definite -set.seed(125) -p <- 0.9 -q <- 0.0 -r <- 0.8 -s <- 0 -t <- 0.1 -u <- 0.2 -chol <- cbind(c(1,p,q,r),c(0,1,s,t),c(0,0,1,u),c(0,0,0,1)) -covvar <- chol%*%t(chol) -covvar -library(mvtnorm) -covvar -eigen(covvar) -chol <- cbind(c(0,p,q,r),c(0,0,s,t),c(0,0,0,u),c(0,0,0,0)) -covvar <- chol%*%t(chol) -covvar -eigen(covvar) -covvar -chol -is.positive.definite(chol) -eigen(covvar) -make.positive.definite(chol) -A <- make.positive.definite(chol) -eigen(A) -A -is.positive.definite(chol) -chol <- cbind(c(0,p,q,r),c(0,0,s,t),c(0,0,0,u),c(0,0,0,0)) -covvar <- chol%*%t(chol) -covvar -chol <- cbind(c(1,p,q,r),c(1,1,s,t),c(1,1,1,u),c(0,0,0,0)) -covvar <- chol%*%t(chol) -covvar -is.positive.definite(chol) -eigen(A) -data <- replicate(rnorm(100),2) -data <- replicate(2,rnorm(100)) -data -cov(data) -cor(data) -plot(data) -eigen(cov(data)) -eigen(cor(data)) -eigenvector <- eigen(cov(data))$vectors -eigenvalues <- eigen(cov(data))$values -abline(a=0,b=eigenvector[2,1]/eigenvector[1,1],col="red") -abline(a=0,b=eigenvector[2,2]/eigenvector[1,2],col="red") -covvar <- cbind(c(2,1),c(1,1)) -data <- rmvnorm(100,mean=c(0,0),sigma=covvar) -eigenvector <- eigen(cov(data))$vectors -eigenvector -eigenvalues <- eigen(cov(data))$values -eigenvalues -plot(data) -abline(a=0,b=eigenvector[2,1]/eigenvector[1,1],col="red") -abline(a=0,b=eigenvector[2,2]/eigenvector[1,2],col="red") -eigenvector <- eigen(cor(data))$vectors -eigenvector -eigenvalues <- eigen(cor(data))$values -eigenvalues -plot(data) -abline(a=0,b=eigenvector[2,1]/eigenvector[1,1],col="red") -abline(a=0,b=eigenvector[2,2]/eigenvector[1,2],col="red") -covvar <- cbind(c(2,-1),c(-1,1)) -data <- rmvnorm(100,mean=c(0,0),sigma=covvar) -eigenvector <- eigen(cor(data))$vectors -eigenvector -eigenvalues <- eigen(cor(data))$values -eigenvalues -plot(data) -abline(a=0,b=eigenvector[2,1]/eigenvector[1,1],col="red") -abline(a=0,b=eigenvector[2,2]/eigenvector[1,2],col="red") -covvar <- cbind(c(0,-1),c(-1,0)) -data <- rmvnorm(100,mean=c(0,0),sigma=covvar) -covvar <- cbind(c(0,1),c(1,0)) -data <- rmvnorm(100,mean=c(0,0),sigma=covvar) -eigen(covvar) -covvar <- cbind(c(0,1,0),c(1,0,1),c(0,1,0)) -covvar -eigen(covvar) -covvar <- cbind(c(1,1,0),c(1,1,1),c(0,1,1)) -covvar -eigen(covvar) -covvar <- cbind(c(2,1,0),c(1,1,1),c(0,1,1)) -covvar -eigen(covvar) -cor(covvar) -covvar <- cbind(c(1,1,0),c(1,1,1),c(0,1,1)) -covvar -eigen(covvar) -cor(covvar) -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,1)) -covvar <- chol%*%t(chol) -covvar -p <- 0.9 -q <- 0.1 -r <- 0.8 -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,1)) -covvar <- chol%*%t(chol) -covvar -is.positive.definite(chol) -eigen(covvar) -covvar -chol <- cbind(c(2,p,q),c(0,1,r),c(0,0,1)) -covvar <- chol%*%t(chol) -covvar -is.positive.definite(chol) -eigen(covvar) -chol <- cbind(c(20,p,q),c(0,1,r),c(0,0,1)) -covvar <- chol%*%t(chol) -covvar -eigen(covvar) -data <- rmvnorm(100,mean=c(0,0,0),sigma=covvar) -install.packages("scatterplot3d") -library(mvtnorm) -library(scatterplot3d) -? scatterplot3d -scatterplot3d(data) -trans3d(data) -trans3d(data[,1],data[,2],data[,3]) -scatterplot3d(data,highlight.3d=TRUE, col.axis="blue", -col.grid="lightblue", main="scatterplot3d - 1", pch=20) -eigen(covvar) -eigenvector <- eigen(cor(data))$vectors -eigenvector -eigenvector <- eigen(cov(data))$vectors -eigenvector -p <- 10 -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,1)) -covvar <- chol%*%t(chol) -covvar -p <- 1 -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,1)) -covvar <- chol%*%t(chol) -covvar -chol <- cbind(c(1,p,q),c(0,0,r),c(0,0,1)) -covvar <- chol%*%t(chol) -covvar -p <- .1 -chol <- cbind(c(1,p,q),c(0,0,r),c(0,0,1)) -covvar <- chol%*%t(chol) -p <- .1 -p <- .1 -q <- 0.1 -r <- 0.8 -chol <- cbind(c(1,p,q),c(0,0,r),c(0,0,1)) -covvar <- chol%*%t(chol) -covvar -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,1)) -covvar <- chol%*%t(chol) -covvar -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,0.7)) -covvar <- chol%*%t(chol) -covvar -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,.65)) -covvar <- chol%*%t(chol) -covvar -is.positive.definite(chol) -eigen(covvar) -r <- 10 -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,.65)) -covvar <- chol%*%t(chol) -covvar -r <- 1 -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,.65)) -covvar <- chol%*%t(chol) -covvar -r <- 0.1 -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,.65)) -covvar <- chol%*%t(chol) -covvar -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,.9)) -covvar <- chol%*%t(chol) -covvar -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,.98)) -covvar <- chol%*%t(chol) -covvar -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,.999)) -covvar <- chol%*%t(chol) -covvar -eigen(covvar) -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,.997)) -covvar <- chol%*%t(chol) -covvar -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,.9999)) -covvar <- chol%*%t(chol) -covvar -r <- 0.5 -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,.9999)) -covvar <- chol%*%t(chol) -covvar -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,.8)) -covvar <- chol%*%t(chol) -covvar -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,.9)) -covvar <- chol%*%t(chol) -covvar -eigen(covvar) -chol <- cbind(c(1,p,q),c(0,1,r),c(0,0,.9)) -data <- rmvnorm(100,mean=c(0,0,0),sigma=covvar) -pc <- princomp(data) -summary(pc) -plot(pc) -loadings(pc) -eigen(cov(data)) -data <- rmvnorm(100,mean=c(1,0,0),sigma=covvar) -eigen(cov(data)) -pc <- princomp(data) -summary(pc) -loadings(pc) -data <- rmvnorm(100,mean=c(0,0,0),sigma=covvar) -# download data small scale experiment -# using the finance sector provided by CNN money -library(quantmod) -library(PerformanceAnalytics) -symbol.vec=c("AAN","AB","ACAS","ACY","AFL","AIG","AMG","AXP","BAC","BGCP", -"C","CCNE","DB","GS","HCC","IHC","JPM","KEY","PLFE","TCHC") -getSymbols(symbol.vec, from ="2000-01-03", to = "2012-05-10") -# extract monthly adjusted closing prices -l <- length(symbol.vec) -db.m.price <- to.monthly(AAN)[, "AAN.Adjusted", drop=FALSE] -colnames(db.m.price) <- "AAN" -db.m.ret <- CalculateReturns(db.m.price, method="compound")[-1,] -for (i in (2:l)) { -name.price <- paste(symbol.vec[i],"m","price",sep=".") -stock <- as.name(symbol.vec[i]) -db.m.new <- to.monthly(eval(stock))[,"eval(stock).Adjusted",drop=FALSE] -colnames(db.m.new) <- symbol.vec[i] -db.m.price <- cbind(db.m.price,db.m.new) -# calculate log-returns -db.m.ret.new <- CalculateReturns(db.m.new, method="compound")[-1,] -db.m.ret <- cbind(db.m.ret,db.m.ret.new) -} -head(db.m.price) -dim(db.m.price) -dim(db.m.ret) -corr.m <- cor(db.m.ret) -corr.m.inv <- solve(corr.m) -db.pc <- princomp(db.m.ret) -summary(db.pc) -centrality <- loadings(db.pc)[,1] -centrality -eigen(corr.m.inv) -centrality -centrality.inv <- eigen(corr.m.inv)$vectors[,1] -eigen(corr.m)$vectors[,1] -cov.m.inv <- solve(cov(db.m.ret)) -centrality.inv <- eigen(cov.m.inv)$vectors[,1] -centrality.inv -eigen(cov(db.m.ret))$vectors[,1] -centrality -centrality.inv -head(db.m.ret) -names(centrality.inv) <- colnames(db.m.ret) -centrality.inv -covvar <- cbind(c(0.8,0.1,0.1),c(0.8,0.1,.1),c(.8,.1,.1)) -covvar -covvar <- cbind(c(0.8,0.8,0.8),c(0.1,0.1,.1),c(.1,.1,.1)) -covvar -eigen(covvar) -covvar <- cbind(c(0.5,0.5,0.5),c(0.4,0.4,.4),c(.1,.1,.1)) -covvar -eigen(covvar) -sum(eigen(covvar)$vectors[,1]^2) -eigen(covvar)$vectors[,1]^2 -sd(eigen(covvar)$vectors[,1]) -covvar <- cbind(replicate(3,c(.33,.33,.33)) -covvar <- cbind(replicate(3,c(.33,.33,.33))) -covvar -covvar <- cbind(replicate(3,c(.33,.33,.33))) -covvar -eigen(covvar) -sd(eigen(covvar)$vectors[,1]) -covvar <- cbind(c(0.5,0.4,0.5),c(0.4,0.5,.4),c(.1,.1,.1)) -covvar -eigen(covvar) -covvar <- cbind(c(0.5,0.4,0.3),c(0.4,0.5,.6),c(.1,.1,.1)) -covvar -eigen(covvar) -sd(eigen(covvar)$vectors[,1]) -covvar <- cbind(c(0.5,0.4,0.3),c(0.4,0.5,.5),c(.1,.1,.2)) -covvar -eigen(covvar) -sd(eigen(covvar)$vectors[,1]) -covvar <- cbind(c(0,0.7,0.5),c(0.9,0,.5),c(.1,0.3,0)) -covvar -eigen(covvar) -eigen(t(covvar) -eigen(t(covvar)) -eigen(t(covvar)) -covvar -t(covvar) -eigen(t(covvar)) -covvar <- cbind(c(0.1,0.7,0.5),c(0.8,0.1,.2),c(.1,0.2,0.3)) -covvar -t(covvar) -eigen(t(covvar)) -sd(eigen(covvar)$vectors[,1]) -eigen(covvar) -t(covvar) -eigen(t(covvar)) -covvar <- cbind(c(0.8,0.8,0.8),c(0.1,0.1,.1),c(.1,0.1,0.1)) -covvar -eigen(covvar) -t(covvar) -eigen(t(covvar)) -sd(eigen(covvar)$vectors[,1]) -sd(eigen(t(covvar))$vectors[,1]) -t(covvar) -library("rmgarch") -? dcc -? DCC.fit -? dccfit -eigen(diag(2)) -eigen(matrix(rep(1,4),nrow=2)) -eigen(matrix(c(1,-1,-1,1),nrow=2)) -covvar <- matrix(rep(1,9),nrow=3) -n <- length(covvar[1,]) -alpha <- eigen(cov(covvar))$values[1] -10^(-3) -solve(diag(n)-alpha*cov(covvar))%*%rep(1,n) -alpha <- eigen(covvar)$values[1] -10^(-3) -solve(diag(n)-alpha*cov(covvar))%*%rep(1,n) -eigen(covvar)$values -alpha <- eigen(covvar)$values[1] -10^(-3) -solve(diag(n)-alpha*cov(covvar))%*%rep(1,n) -kalz <- function(covvar) { -n <- length(covvar[1,]) -alpha <- eigen(covvar)$values[1] -10^(-3) -kalz.ec <- solve(diag(n)-alpha*cov(covvar))%*%rep(1,n) -return(kalz.ec) -} -kalz(covvar) -covvar2 <- matrix(rep(.1,9),nrow=3) -kalz(covvar2) -kalz <- function(covvar) { -n <- length(covvar[1,]) -alpha <- eigen(covvar)$values[1] -10^(-1) -kalz.ec <- solve(diag(n)-alpha*cov(covvar))%*%rep(1,n) -return(kalz.ec) -} -# example of all 1 matrix -covvar <- matrix(rep(1,9),nrow=3) -kalz(covvar) -# example of all .1 matrix -covvar2 <- matrix(rep(.1,9),nrow=3) -kalz(covvar2) -kalz <- function(covvar) { -n <- length(covvar[1,]) -alpha <- eigen(covvar)$values[1] -10^(-2) -kalz.ec <- solve(diag(n)-alpha*cov(covvar))%*%rep(1,n) -return(kalz.ec) -} -# example of all 1 matrix -covvar <- matrix(rep(1,9),nrow=3) -kalz(covvar) -# example of all .1 matrix -covvar2 <- matrix(rep(.1,9),nrow=3) -kalz(covvar2) -covvar3 <- eigen(matrix(c(1,0,0,0,1,0,0,0,1),nrow=3)) -covvar3 -covvar3 <- matrix(c(1,0,0,0,1,0,0,0,1),nrow=3) -covvar3 -kalz(covvar3) -covvar -covvar2 -covvar2 <- matrix(c(1,0.1,0.1,0.1,1,0.1,0.1,0.1,1),nrow=3) -kalz(covvar2) -covvar2 <- matrix(c(1,0.1,0.1,0.1,1,0.1,0.1,0.1,1),nrow=3) -kalz(covvar2) -covvar2 -diag(covvar2) <- c(0,0,0) -covvar2 -kalz(covvar2) -matrix(c(1,1,-1,1,1,-1,-1,-1,1),nrow=3) -covvar4 <- matrix(c(1,1,-1,1,1,-1,-1,-1,1),nrow=3) -kalz(covvar4) -covvar4 -kalz(matrix(c(1,1,-.1,1,1,-.1,-.1,-.1,1),nrow=3)) -matrix(c(1,1,-.1,1,1,-.1,-.1,-.1,1),nrow=3) -kalz(matrix(c(1,1,.1,1,1,.1,.1,.1,1),nrow=3)) -kalz <- function(covvar) { -n <- length(covvar[1,]) -alpha <- (eigen(covvar)$values[1])^(-1) -10^(-2) -kalz.ec <- solve(diag(n)-alpha*cov(covvar))%*%rep(1,n) -return(kalz.ec) -} -covvar <- matrix(rep(1,9),nrow=3) -kalz(covvar) -covvar2 <- matrix(c(1,0.1,0.1,0.1,1,0.1,0.1,0.1,1),nrow=3) -kalz(covvar2) -covvar3 <- matrix(c(1,0,0,0,1,0,0,0,1),nrow=3) -kalz(covvar3) -covvar4 <- matrix(c(1,1,-1,1,1,-1,-1,-1,1),nrow=3) -kalz(covvar4) -kalz(matrix(c(1,1,-.1,1,1,-.1,-.1,-.1,1),nrow=3)) -kalz(matrix(c(1,1,.1,1,1,.1,.1,.1,1),nrow=3)) -covvar4 <- matrix(c(1,1,-1,1,1,-1,-1,-1,1),nrow=3) -kalz(covvar4) -covvar4 <- matrix(c(1,1,-.9,1,1,-.9,-.9,-.9,1),nrow=3) -kalz(covvar4) -kalz(matrix(c(1,1,-.1,1,1,-.1,-.1,-.1,1),nrow=3)) -kalz(matrix(c(1,1,-1,1,1,-1,-1,-1,1),nrow=3)) -kalz(matrix(c(1,1,-1,1,1,-1,-1,-1,1),nrow=3)) -kalz(matrix(c(1,1,-.1,1,1,-.1,-.1,-.1,1),nrow=3)) -kalz(matrix(c(1,1,.1,1,1,.1,.1,.1,1),nrow=3)) -matrix(c(1,1,.1,1,1,.1,.1,.1,1),nrow=3) -kalz(matrix(c(1,1,0,1,1,0,0,0,1),nrow=3) -kalz(matrix(c(1,1,0,1,1,0,0,0,1),nrow=3)) -########################################################### -kalz(matrix(c(1,1,0,1,1,0,0,0,1),nrow=3)) -matrix(c(1,1,0,1,1,0,0,0,1),nrow=3) -########################################################### -kalz(matrix(c(1,1,-1,1,1,-1,-1,-1,1),nrow=3)) -kalz(matrix(c(1,1,-.1,1,1,-.1,-.1,-.1,1),nrow=3)) -kalz(matrix(c(1,1,.5,1,1,.5,.5,.5,1),nrow=3)) -kalz(matrix(c(1,1,-.5,1,1,-.5,-.5,-.5,1),nrow=3)) -kalz(matrix(c(1,1,.9,1,1,.9,.9,.9,1),nrow=3)) -kalz(matrix(c(1,1,-.9,1,1,-.9,-.9,-.9,1),nrow=3)) -library(matrixcalc) -install.packages("matrixcalc") -is.positive.definite(matrix(c(1,1,-.1,1,1,-.1,-.1,-.1,1),nrow=3)) -is.positive.definite(matrix(c(1,1,-1,1,1,-1,-1,-1,1),nrow=3)) -library(matrixcalc) -is.positive.definite(matrix(c(1,1,-1,1,1,-1,-1,-1,1),nrow=3)) -is.positive.definite(matrix(c(1,1,-.1,1,1,-.1,-.1,-.1,1),nrow=3)) -is.positive.definite(matrix(c(1,1,.1,1,1,.1,.1,.1,1),nrow=3)) -is.positive.definite(matrix(c(1,1,0,1,1,0,0,0,1),nrow=3)) -is.positive.definite(matrix(c(1,1,0,1,1,0,0,0,1),nrow=3)) -is.positive.definite(diag(3)) -is.positive.definite(matrix(c(1,1,-1,1,1,-1,-1,-1,1),nrow=3)) -library(mvtnorm) -library(sna) -library(matrixcalc) -library(corpcor) -chol <- cbind(c(1,0.1,0.1,0.1,0.1),c(0,0.99,0.1,0.1,0.2),c(0,0,0.98,0.4,0.5), -c(0,0,0,0.9,0.5),c(0,0,0,0,0.7)) -covvar <- chol%*%t(chol) -covvar -is.positive.definite(covvar) -eigen(covvar) -eigen(solve(covvar)) -is.positive.definite(covvar) -gplot(covvar,gmode="graph",edge.lwd=15,label=c(1,2,3,4,5)) -eigen(covvar) -? gplot -install.packages(c("JGR","Deducer","DeducerExtras")) -library(JGR) -JGR() -install.packages("rJava") -JPR() -JGR() -library(JGR) -plot.lm -? plot.ts -? plotcorr -install.packages("ellipse") -install.packages("strucchange") -library(ellipse) -? plotcorr -setwd("C:/Users/Yi-An Chen/Documents/R-project/returnanalytics/pkg/FactorAnalytics/data") -load("stat.fm.data.RData") -setwd("C:/Users/Yi-An Chen/Documents/R-project/factoranalytics/pkg/factorAnalytics/R") -source("fitStatisticalFactorModel.r") -source("print.StatFactorModel.r") -sfm.pca.fit <- fitStatisticalFactorModel(sfm.dat,k=10) -source("plot.StatFactorModel.r") -plot(sfm.pca.fit) -source("plot.StatFactorModel.r") -plot(sfm.pca.fit) -plot(sfm.pca.fit) -plot(sfm.pca.fit) -source("factorModelCovariance.r") -source("factorModelSdDecomposition.r") -source("factorModelEsDecomposition.r") -source("factorModelVaRDecomposition.r") -plot(sfm.pca.fit) -plot(sfm.pca.fit) -plot(sfm.pca.fit) -plot(sfm.pca.fit) -plot(sfm.pca.fit) -plot(sfm.pca.fit) -plot(sfm.pca.fit) -plot(sfm.pca.fit) -plot(sfm.pca.fit) -plot(sfm.pca.fit) -plot(sfm.pca.fit) -plot(sfm.pca.fit) -plot(sfm.pca.fit) -plot(sfm.pca.fit) -setwd("C:/Users/Yi-An Chen/Documents/R-project/returnanalytics/pkg/FactorAnalytics/data") -load("stock.RData") -setwd("C:/Users/Yi-An Chen/Documents/R-project/returnanalytics/pkg/FactorAnalytics/R") -source("fitFundamentalFactorModel.r") -assets = unique(fulldata[,"PERMNO"]) -timedates = as.Date(unique(fulldata[,"DATE"])) -exposures <- exposures.names <- c("BOOK2MARKET", "LOG.MARKETCAP") -? data -data(stock) -setwd("C:/Users/Yi-An Chen/Documents/R-project/returnanalytics/pkg/FactorAnalytics/data") -data(stock) From noreply at r-forge.r-project.org Fri Feb 21 04:51:08 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 21 Feb 2014 04:51:08 +0100 (CET) Subject: [Returnanalytics-commits] r3324 - pkg/FactorAnalytics Message-ID: <20140221035108.C940F1869CD@r-forge.r-project.org> Author: efmrforge Date: 2014-02-21 04:51:05 +0100 (Fri, 21 Feb 2014) New Revision: 3324 Added: pkg/FactorAnalytics/.Rbuildignore Log: Added .Rbuildignore file to not include sandbox and .svn Added: pkg/FactorAnalytics/.Rbuildignore =================================================================== --- pkg/FactorAnalytics/.Rbuildignore (rev 0) +++ pkg/FactorAnalytics/.Rbuildignore 2014-02-21 03:51:05 UTC (rev 3324) @@ -0,0 +1,7 @@ +^\.svn$ +^sandbox/*$ +^R/\.svn$ +^data/\.svn$ +^inst/\.svn$ +^man/\.svn$ +^vignettes/\.svn$ From noreply at r-forge.r-project.org Fri Feb 21 04:59:23 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 21 Feb 2014 04:59:23 +0100 (CET) Subject: [Returnanalytics-commits] r3325 - pkg/FactorAnalytics Message-ID: <20140221035923.94288186D8F@r-forge.r-project.org> Author: efmrforge Date: 2014-02-21 04:59:22 +0100 (Fri, 21 Feb 2014) New Revision: 3325 Modified: pkg/FactorAnalytics/DESCRIPTION Log: Added zoo to Depends Modified: pkg/FactorAnalytics/DESCRIPTION =================================================================== --- pkg/FactorAnalytics/DESCRIPTION 2014-02-21 03:51:05 UTC (rev 3324) +++ pkg/FactorAnalytics/DESCRIPTION 2014-02-21 03:59:22 UTC (rev 3325) @@ -7,5 +7,5 @@ Maintainer: Yi-An Chen Description: An R package for estimation and risk analysis of linear factor models for asset returns and portfolios. It contains three major fitting method for the factor models: fitting macroeconomic factor model, fitting fundamental factor model and fitting statistical factor model and some risk analysis tools like VaR, ES to use the result of the fitting method. It also provides the different type of distribution to fit the fat-tail behavior of the financial returns, including edgeworth expansion type distribution. License: GPL-2 -Depends: robust, robustbase, leaps, lars,ff, MASS, PerformanceAnalytics, sn, tseries, strucchange,xts,ellipse -LazyLoad: yes \ No newline at end of file +Depends: robust, robustbase, leaps, lars,ff, MASS, PerformanceAnalytics, sn, tseries, strucchange,xts,ellipse, zoo +LazyLoad: yes From noreply at r-forge.r-project.org Fri Feb 21 22:49:57 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 21 Feb 2014 22:49:57 +0100 (CET) Subject: [Returnanalytics-commits] r3326 - in pkg/PerformanceAnalytics: . R sandbox/Shubhankit Message-ID: <20140221214957.7F368186CC1@r-forge.r-project.org> Author: peter_carl Date: 2014-02-21 22:49:56 +0100 (Fri, 21 Feb 2014) New Revision: 3326 Modified: pkg/PerformanceAnalytics/ pkg/PerformanceAnalytics/R/legend.R pkg/PerformanceAnalytics/sandbox/Shubhankit/ Log: - added alias tags for tol colors Property changes on: pkg/PerformanceAnalytics ___________________________________________________________________ Added: svn:ignore + .Rproj.user .Rhistory .RData Modified: pkg/PerformanceAnalytics/R/legend.R =================================================================== --- pkg/PerformanceAnalytics/R/legend.R 2014-02-21 03:59:22 UTC (rev 3325) +++ pkg/PerformanceAnalytics/R/legend.R 2014-02-21 21:49:56 UTC (rev 3326) @@ -20,7 +20,10 @@ #' rich12equal rich6equal rich8equal set6equal set8equal tim10equal tim12equal #' tim6equal tim8equal bond.dates bond.labels cycles.dates equity.dates #' equity.labels macro.dates macro.labels risk.dates risk.labels allsymbols -#' closedsymbols fillsymbols linesymbols opensymbols +#' closedsymbols fillsymbols linesymbols opensymbols tol1qualitative tol2qualitative tol3qualitative +#' tol4qualitative tol5qualitative tol6qualitative tol7qualitative tol8qualitative tol9qualitative +#' tol10qualitative tol11qualitative tol12qualitative +#' tol14rainbow tol15rainbow tol18rainbow tol21rainbow #' @param x,y the x and y co-ordinates to be used to position the legend. They #' can be specified by keyword or in any way which is accepted by #' \code{\link{xy.coords}}: See Details. Property changes on: pkg/PerformanceAnalytics/sandbox/Shubhankit ___________________________________________________________________ Added: svn:ignore + .Rproj.user .Rhistory .RData From noreply at r-forge.r-project.org Fri Feb 21 22:52:05 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 21 Feb 2014 22:52:05 +0100 (CET) Subject: [Returnanalytics-commits] r3327 - pkg/PerformanceAnalytics/R Message-ID: <20140221215205.BFF401802F0@r-forge.r-project.org> Author: peter_carl Date: 2014-02-21 22:52:05 +0100 (Fri, 21 Feb 2014) New Revision: 3327 Modified: pkg/PerformanceAnalytics/R/CAPM.alpha.R Log: - added alias for SFM.alpha Modified: pkg/PerformanceAnalytics/R/CAPM.alpha.R =================================================================== --- pkg/PerformanceAnalytics/R/CAPM.alpha.R 2014-02-21 21:49:56 UTC (rev 3326) +++ pkg/PerformanceAnalytics/R/CAPM.alpha.R 2014-02-21 21:52:05 UTC (rev 3327) @@ -10,6 +10,7 @@ #' literature, it is an example of a simple single factor model, #' comparing an asset to any arbitrary benchmark. #' +#' @aliases SFM.alpha #' @param Ra an xts, vector, matrix, data frame, timeSeries or zoo object of #' asset returns #' @param Rb return vector of the benchmark asset From noreply at r-forge.r-project.org Fri Feb 21 22:52:57 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 21 Feb 2014 22:52:57 +0100 (CET) Subject: [Returnanalytics-commits] r3328 - pkg/PerformanceAnalytics/R Message-ID: <20140221215257.1DC2D186CE0@r-forge.r-project.org> Author: peter_carl Date: 2014-02-21 22:52:56 +0100 (Fri, 21 Feb 2014) New Revision: 3328 Modified: pkg/PerformanceAnalytics/R/CAPM.beta.R Log: - added alias for SFM.beta Modified: pkg/PerformanceAnalytics/R/CAPM.beta.R =================================================================== --- pkg/PerformanceAnalytics/R/CAPM.beta.R 2014-02-21 21:52:05 UTC (rev 3327) +++ pkg/PerformanceAnalytics/R/CAPM.beta.R 2014-02-21 21:52:56 UTC (rev 3328) @@ -31,7 +31,7 @@ #' literature, it is an example of a simple single factor model, #' comparing an asset to any arbitrary benchmark. #' -#' @aliases CAPM.beta CAPM.beta.bull CAPM.beta.bear TimingRatio +#' @aliases CAPM.beta CAPM.beta.bull CAPM.beta.bear TimingRatio SFM.beta #' @param Ra an xts, vector, matrix, data frame, timeSeries or zoo object of #' asset returns #' @param Rb return vector of the benchmark asset From noreply at r-forge.r-project.org Fri Feb 21 22:57:33 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 21 Feb 2014 22:57:33 +0100 (CET) Subject: [Returnanalytics-commits] r3329 - pkg/PerformanceAnalytics/R Message-ID: <20140221215733.303EB186D06@r-forge.r-project.org> Author: peter_carl Date: 2014-02-21 22:57:32 +0100 (Fri, 21 Feb 2014) New Revision: 3329 Modified: pkg/PerformanceAnalytics/R/CAPM.dynamic.R pkg/PerformanceAnalytics/R/CAPM.epsilon.R pkg/PerformanceAnalytics/R/CAPM.jensenAlpha.R Log: - added alias for SFM nomenclature Modified: pkg/PerformanceAnalytics/R/CAPM.dynamic.R =================================================================== --- pkg/PerformanceAnalytics/R/CAPM.dynamic.R 2014-02-21 21:52:56 UTC (rev 3328) +++ pkg/PerformanceAnalytics/R/CAPM.dynamic.R 2014-02-21 21:57:32 UTC (rev 3329) @@ -27,6 +27,7 @@ #' \deqn{r_{pt+1}=\alpha_{0p}+A_{p}'z_{t}+b_{0p}r_{bt+1}+B_{p}'[z_{t}r_{bt+1}]+ #' \mu_{pt+1}} #' +#' @aliases SFM.dynamic #' @param Ra an xts, vector, matrix, data frame, timeSeries or zoo object of #' the asset returns #' @param Rb an xts, vector, matrix, data frame, timeSeries or zoo object of Modified: pkg/PerformanceAnalytics/R/CAPM.epsilon.R =================================================================== --- pkg/PerformanceAnalytics/R/CAPM.epsilon.R 2014-02-21 21:52:56 UTC (rev 3328) +++ pkg/PerformanceAnalytics/R/CAPM.epsilon.R 2014-02-21 21:57:32 UTC (rev 3329) @@ -8,7 +8,7 @@ #' where \eqn{\alpha_r} is the regression alpha, \eqn{\beta_r} is the regression beta, #' \eqn{r_p} is the portfolio return and b is the benchmark return #' -#' @aliases Regression epsilon +#' @aliases SFM.epsilon #' @param Ra an xts, vector, matrix, data frame, timeSeries or zoo object of #' asset returns #' @param Rb return vector of the benchmark asset Modified: pkg/PerformanceAnalytics/R/CAPM.jensenAlpha.R =================================================================== --- pkg/PerformanceAnalytics/R/CAPM.jensenAlpha.R 2014-02-21 21:52:56 UTC (rev 3328) +++ pkg/PerformanceAnalytics/R/CAPM.jensenAlpha.R 2014-02-21 21:57:32 UTC (rev 3329) @@ -8,7 +8,7 @@ #' where \eqn{r_f} is the risk free rate, \eqn{\beta_r} is the regression beta, #' \eqn{r_p} is the portfolio return and b is the benchmark return #' -#' @aliases Jensen'sAlpha +#' @aliases SFM.jensenAlpha #' @param Ra an xts, vector, matrix, data frame, timeSeries or zoo object of #' asset returns #' @param Rb return vector of the benchmark asset From noreply at r-forge.r-project.org Sat Feb 22 04:15:54 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sat, 22 Feb 2014 04:15:54 +0100 (CET) Subject: [Returnanalytics-commits] r3330 - pkg/FactorAnalytics/R Message-ID: <20140222031554.EABCF185613@r-forge.r-project.org> Author: efmrforge Date: 2014-02-22 04:15:53 +0100 (Sat, 22 Feb 2014) New Revision: 3330 Modified: pkg/FactorAnalytics/R/factorModelMonteCarlo.R Log: Fixed error in rst parameter names Modified: pkg/FactorAnalytics/R/factorModelMonteCarlo.R =================================================================== --- pkg/FactorAnalytics/R/factorModelMonteCarlo.R 2014-02-21 21:57:32 UTC (rev 3329) +++ pkg/FactorAnalytics/R/factorModelMonteCarlo.R 2014-02-22 03:15:53 UTC (rev 3330) @@ -144,10 +144,10 @@ } else if (residual.dist == "skew-t") { ## residual distribution is CornishFisher residualsSim[, i] = rst(n.boot, - location=residualData[i, "location"], - scale=residualData[i,"scale"], - shape=residualData[i,"shape"], - df=residualData[i,"df"]) + xi=residualData[i, "location"], + omega=residualData[i,"scale"], + alpha=residualData[i,"shape"], + nu=residualData[i,"df"]) } else { stop("Invalid residual distribution") } From noreply at r-forge.r-project.org Sat Feb 22 04:32:43 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sat, 22 Feb 2014 04:32:43 +0100 (CET) Subject: [Returnanalytics-commits] r3331 - pkg/PApages Message-ID: <20140222033243.EFFEE186C83@r-forge.r-project.org> Author: efmrforge Date: 2014-02-22 04:32:41 +0100 (Sat, 22 Feb 2014) New Revision: 3331 Modified: pkg/PApages/DESCRIPTION Log: Added fBasics and gplots to Depends Modified: pkg/PApages/DESCRIPTION =================================================================== --- pkg/PApages/DESCRIPTION 2014-02-22 03:15:53 UTC (rev 3330) +++ pkg/PApages/DESCRIPTION 2014-02-22 03:32:41 UTC (rev 3331) @@ -8,7 +8,7 @@ Description: Creates formatted views of performance and risk information using PerformanceAnalytics and other packages. This is considered EXPERIMENTAL CODE and WILL NOT BE SUPPORTED. Collaboration towards creating a supportable code base would be welcome, however. License: GPL LazyLoad: yes -Depends: R (>= 2.4.0), PerformanceAnalytics (>= 1.0.3.3), gtools, Hmisc, sn +Depends: R (>= 2.4.0), PerformanceAnalytics (>= 1.0.3.3), gtools, Hmisc, sn, fBasics, gplots Suggests: URL: http://r-forge.r-project.org/projects/returnanalytics/ Copyright: (c) 2004-2011 From noreply at r-forge.r-project.org Sun Feb 23 13:51:49 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 23 Feb 2014 13:51:49 +0100 (CET) Subject: [Returnanalytics-commits] r3332 - in pkg/PerformanceAnalytics: . R man Message-ID: <20140223125149.4D75D1869D1@r-forge.r-project.org> Author: braverock Date: 2014-02-23 13:51:48 +0100 (Sun, 23 Feb 2014) New Revision: 3332 Modified: pkg/PerformanceAnalytics/DESCRIPTION pkg/PerformanceAnalytics/NAMESPACE pkg/PerformanceAnalytics/R/DownsideDeviation.R pkg/PerformanceAnalytics/R/Return.calculate.R pkg/PerformanceAnalytics/R/StdDev.annualized.R pkg/PerformanceAnalytics/R/chart.Events.R pkg/PerformanceAnalytics/R/table.CaptureRatios.R pkg/PerformanceAnalytics/R/table.UpDownRatios.R pkg/PerformanceAnalytics/man/ActivePremium.Rd pkg/PerformanceAnalytics/man/AdjustedSharpeRatio.Rd pkg/PerformanceAnalytics/man/AppraisalRatio.Rd pkg/PerformanceAnalytics/man/AverageDrawdown.Rd pkg/PerformanceAnalytics/man/BernardoLedoitRatio.Rd pkg/PerformanceAnalytics/man/BetaCoMoments.Rd pkg/PerformanceAnalytics/man/BurkeRatio.Rd pkg/PerformanceAnalytics/man/CAPM.RiskPremium.Rd pkg/PerformanceAnalytics/man/CAPM.alpha.Rd pkg/PerformanceAnalytics/man/CAPM.beta.Rd pkg/PerformanceAnalytics/man/CAPM.dynamic.Rd pkg/PerformanceAnalytics/man/CAPM.epsilon.Rd pkg/PerformanceAnalytics/man/CAPM.jensenAlpha.Rd pkg/PerformanceAnalytics/man/CDD.Rd pkg/PerformanceAnalytics/man/CalmarRatio.Rd pkg/PerformanceAnalytics/man/CoMoments.Rd pkg/PerformanceAnalytics/man/DRatio.Rd pkg/PerformanceAnalytics/man/DownsideDeviation.Rd pkg/PerformanceAnalytics/man/DownsideFrequency.Rd pkg/PerformanceAnalytics/man/DrawdownDeviation.Rd pkg/PerformanceAnalytics/man/DrawdownPeak.Rd pkg/PerformanceAnalytics/man/ES.Rd pkg/PerformanceAnalytics/man/FamaBeta.Rd pkg/PerformanceAnalytics/man/Frequency.Rd pkg/PerformanceAnalytics/man/HurstIndex.Rd pkg/PerformanceAnalytics/man/InformationRatio.Rd pkg/PerformanceAnalytics/man/Kappa.Rd pkg/PerformanceAnalytics/man/KellyRatio.Rd pkg/PerformanceAnalytics/man/M2Sortino.Rd pkg/PerformanceAnalytics/man/MSquared.Rd pkg/PerformanceAnalytics/man/MSquaredExcess.Rd pkg/PerformanceAnalytics/man/MarketTiming.Rd pkg/PerformanceAnalytics/man/MartinRatio.Rd pkg/PerformanceAnalytics/man/MeanAbsoluteDeviation.Rd pkg/PerformanceAnalytics/man/Modigliani.Rd pkg/PerformanceAnalytics/man/NetSelectivity.Rd pkg/PerformanceAnalytics/man/Omega.Rd pkg/PerformanceAnalytics/man/OmegaExcessReturn.Rd pkg/PerformanceAnalytics/man/OmegaSharpeRatio.Rd pkg/PerformanceAnalytics/man/PainIndex.Rd pkg/PerformanceAnalytics/man/PainRatio.Rd pkg/PerformanceAnalytics/man/ProspectRatio.Rd pkg/PerformanceAnalytics/man/Return.Geltner.Rd pkg/PerformanceAnalytics/man/Return.annualized.Rd pkg/PerformanceAnalytics/man/Return.annualized.excess.Rd pkg/PerformanceAnalytics/man/Return.calculate.Rd pkg/PerformanceAnalytics/man/Return.clean.Rd pkg/PerformanceAnalytics/man/Return.cumulative.Rd pkg/PerformanceAnalytics/man/Return.excess.Rd pkg/PerformanceAnalytics/man/Return.portfolio.Rd pkg/PerformanceAnalytics/man/Return.read.Rd pkg/PerformanceAnalytics/man/Return.relative.Rd pkg/PerformanceAnalytics/man/Selectivity.Rd pkg/PerformanceAnalytics/man/SharpeRatio.Rd pkg/PerformanceAnalytics/man/SharpeRatio.annualized.Rd pkg/PerformanceAnalytics/man/SkewnessKurtosisRatio.Rd pkg/PerformanceAnalytics/man/SmoothingIndex.Rd pkg/PerformanceAnalytics/man/SortinoRatio.Rd pkg/PerformanceAnalytics/man/SpecificRisk.Rd pkg/PerformanceAnalytics/man/StdDev.Rd pkg/PerformanceAnalytics/man/StdDev.annualized.Rd pkg/PerformanceAnalytics/man/SystematicRisk.Rd pkg/PerformanceAnalytics/man/TotalRisk.Rd pkg/PerformanceAnalytics/man/TrackingError.Rd pkg/PerformanceAnalytics/man/TreynorRatio.Rd pkg/PerformanceAnalytics/man/UlcerIndex.Rd pkg/PerformanceAnalytics/man/UpDownRatios.Rd pkg/PerformanceAnalytics/man/UpsideFrequency.Rd pkg/PerformanceAnalytics/man/UpsidePotentialRatio.Rd pkg/PerformanceAnalytics/man/UpsideRisk.Rd pkg/PerformanceAnalytics/man/VaR.Rd pkg/PerformanceAnalytics/man/VolatilitySkewness.Rd pkg/PerformanceAnalytics/man/apply.fromstart.Rd pkg/PerformanceAnalytics/man/apply.rolling.Rd pkg/PerformanceAnalytics/man/centeredmoments.Rd pkg/PerformanceAnalytics/man/chart.ACF.Rd pkg/PerformanceAnalytics/man/chart.Bar.Rd pkg/PerformanceAnalytics/man/chart.BarVaR.Rd pkg/PerformanceAnalytics/man/chart.Boxplot.Rd pkg/PerformanceAnalytics/man/chart.CaptureRatios.Rd pkg/PerformanceAnalytics/man/chart.Correlation.Rd pkg/PerformanceAnalytics/man/chart.CumReturns.Rd pkg/PerformanceAnalytics/man/chart.Drawdown.Rd pkg/PerformanceAnalytics/man/chart.ECDF.Rd pkg/PerformanceAnalytics/man/chart.Events.Rd pkg/PerformanceAnalytics/man/chart.Histogram.Rd pkg/PerformanceAnalytics/man/chart.QQPlot.Rd pkg/PerformanceAnalytics/man/chart.Regression.Rd pkg/PerformanceAnalytics/man/chart.RelativePerformance.Rd pkg/PerformanceAnalytics/man/chart.RiskReturnScatter.Rd pkg/PerformanceAnalytics/man/chart.RollingCorrelation.Rd pkg/PerformanceAnalytics/man/chart.RollingMean.Rd pkg/PerformanceAnalytics/man/chart.RollingPerformance.Rd pkg/PerformanceAnalytics/man/chart.RollingRegression.Rd pkg/PerformanceAnalytics/man/chart.Scatter.Rd pkg/PerformanceAnalytics/man/chart.SnailTrail.Rd pkg/PerformanceAnalytics/man/chart.StackedBar.Rd pkg/PerformanceAnalytics/man/chart.TimeSeries.Rd pkg/PerformanceAnalytics/man/chart.VaRSensitivity.Rd pkg/PerformanceAnalytics/man/charts.PerformanceSummary.Rd pkg/PerformanceAnalytics/man/charts.RollingPerformance.Rd pkg/PerformanceAnalytics/man/checkData.Rd pkg/PerformanceAnalytics/man/clean.boudt.Rd pkg/PerformanceAnalytics/man/findDrawdowns.Rd pkg/PerformanceAnalytics/man/kurtosis.Rd pkg/PerformanceAnalytics/man/legend.Rd pkg/PerformanceAnalytics/man/lpm.Rd pkg/PerformanceAnalytics/man/maxDrawdown.Rd pkg/PerformanceAnalytics/man/mean.geometric.Rd pkg/PerformanceAnalytics/man/skewness.Rd pkg/PerformanceAnalytics/man/sortDrawdowns.Rd pkg/PerformanceAnalytics/man/table.AnnualizedReturns.Rd pkg/PerformanceAnalytics/man/table.Arbitrary.Rd pkg/PerformanceAnalytics/man/table.Autocorrelation.Rd pkg/PerformanceAnalytics/man/table.CAPM.Rd pkg/PerformanceAnalytics/man/table.CalendarReturns.Rd pkg/PerformanceAnalytics/man/table.CaptureRatios.Rd pkg/PerformanceAnalytics/man/table.Correlation.Rd pkg/PerformanceAnalytics/man/table.Distributions.Rd pkg/PerformanceAnalytics/man/table.DownsideRisk.Rd pkg/PerformanceAnalytics/man/table.DownsideRiskRatio.Rd pkg/PerformanceAnalytics/man/table.Drawdowns.Rd pkg/PerformanceAnalytics/man/table.DrawdownsRatio.Rd pkg/PerformanceAnalytics/man/table.HigherMoments.Rd pkg/PerformanceAnalytics/man/table.InformationRatio.Rd pkg/PerformanceAnalytics/man/table.MonthlyReturns.Rd pkg/PerformanceAnalytics/man/table.RollingPeriods.Rd pkg/PerformanceAnalytics/man/table.SpecificRisk.Rd pkg/PerformanceAnalytics/man/table.Variability.Rd pkg/PerformanceAnalytics/man/textplot.Rd pkg/PerformanceAnalytics/man/zerofill.Rd Log: - updates ahead of CRAN release Modified: pkg/PerformanceAnalytics/DESCRIPTION =================================================================== --- pkg/PerformanceAnalytics/DESCRIPTION 2014-02-22 03:32:41 UTC (rev 3331) +++ pkg/PerformanceAnalytics/DESCRIPTION 2014-02-23 12:51:48 UTC (rev 3332) @@ -1,7 +1,7 @@ Package: PerformanceAnalytics Type: Package Title: Econometric tools for performance and risk analysis. -Version: 1.1.3 +Version: 1.1.4 Date: $Date$ Author: Peter Carl, Brian G. Peterson Maintainer: Brian G. Peterson @@ -21,7 +21,7 @@ Suggests: Hmisc, MASS, - tseries, + quantmod, quadprog, gamlss, robustbase, Modified: pkg/PerformanceAnalytics/NAMESPACE =================================================================== --- pkg/PerformanceAnalytics/NAMESPACE 2014-02-22 03:32:41 UTC (rev 3331) +++ pkg/PerformanceAnalytics/NAMESPACE 2014-02-23 12:51:48 UTC (rev 3332) @@ -34,6 +34,7 @@ export(DRatio) export(DownsideDeviation) export(DownsideFrequency) +export(DownsidePotential) export(DrawdownDeviation) export(DrawdownPeak) export(ES) @@ -181,6 +182,8 @@ export(rich8equal) export(risk.dates) export(risk.labels) +export(sd.annualized) +export(sd.multiperiod) export(set6equal) export(set8equal) export(skewness) @@ -203,6 +206,7 @@ export(table.SpecificRisk) export(table.Stats) export(table.TrailingPeriods) +export(table.UpDownRatios) export(table.Variability) export(textplot) export(tim10equal) @@ -225,6 +229,7 @@ export(tol7qualitative) export(tol8qualitative) export(tol9qualitative) +export(zerofill) importFrom(stats,sd) importFrom(utils,packageDescription) importFrom(zoo,rollapply) Modified: pkg/PerformanceAnalytics/R/DownsideDeviation.R =================================================================== --- pkg/PerformanceAnalytics/R/DownsideDeviation.R 2014-02-22 03:32:41 UTC (rev 3331) +++ pkg/PerformanceAnalytics/R/DownsideDeviation.R 2014-02-23 12:51:48 UTC (rev 3332) @@ -156,6 +156,8 @@ } } +#' @rdname DownsideDeviation +#' @export DownsidePotential <- function (R, MAR=0) { # @author Peter Carl, Matthieu Lestel Modified: pkg/PerformanceAnalytics/R/Return.calculate.R =================================================================== --- pkg/PerformanceAnalytics/R/Return.calculate.R 2014-02-22 03:32:41 UTC (rev 3331) +++ pkg/PerformanceAnalytics/R/Return.calculate.R 2014-02-23 12:51:48 UTC (rev 3332) @@ -41,8 +41,8 @@ #' @examples #' #' \dontrun{ -#' require(tseries) -#' prices = get.hist.quote("IBM", start = "1999-01-01", end = "2007-01-01", quote = "AdjClose", compression = "d") +#' require(quantmod) +#' prices = getSymbols("IBM", from = "1999-01-01", to = "2007-01-01") #' } #' \dontshow{ #' data(prices) Modified: pkg/PerformanceAnalytics/R/StdDev.annualized.R =================================================================== --- pkg/PerformanceAnalytics/R/StdDev.annualized.R 2014-02-22 03:32:41 UTC (rev 3331) +++ pkg/PerformanceAnalytics/R/StdDev.annualized.R 2014-02-23 12:51:48 UTC (rev 3332) @@ -44,7 +44,8 @@ #' # now for three periods: #' sd.multiperiod(edhec[,6,drop=FALSE],scale=3) #' -#' @export +#' @export StdDev.annualized sd.annualized sd.multiperiod +#' @alias StdDev.annualized sd.annualized sd.multiperiod #' @rdname StdDev.annualized StdDev.annualized <- sd.annualized <- sd.multiperiod <- function (x, scale = NA, ...) Modified: pkg/PerformanceAnalytics/R/chart.Events.R =================================================================== --- pkg/PerformanceAnalytics/R/chart.Events.R 2014-02-22 03:32:41 UTC (rev 3331) +++ pkg/PerformanceAnalytics/R/chart.Events.R 2014-02-23 12:51:48 UTC (rev 3332) @@ -33,17 +33,17 @@ #' \code{\link{par}} #' @keywords ts hplot #' @examples -#' +#' \dontrun{ #' data(managers) -#' R = Drawdowns(managers[,2,drop=FALSE]) +#' R = PerformanceAnalytics:::Drawdowns(managers[,2,drop=FALSE]) #' n = table.Drawdowns(managers[,2,drop=FALSE]) -#' chart.Events(Drawdowns(managers[,2,drop=FALSE]), +#' chart.Events(PerformanceAnalytics:::Drawdowns(managers[,2,drop=FALSE]), #' dates = n$Trough, #' prior=max(na.omit(n$"To Trough")), #' post=max(na.omit(n$Recovery)), #' lwd=2, colorset=redfocus, legend.loc=NULL, #' main = "Worst Drawdowns") -#' +#' } #' @export chart.Events <- function (R, dates, prior=12, post=12, main = NULL, xlab=NULL, ...) Modified: pkg/PerformanceAnalytics/R/table.CaptureRatios.R =================================================================== --- pkg/PerformanceAnalytics/R/table.CaptureRatios.R 2014-02-22 03:32:41 UTC (rev 3331) +++ pkg/PerformanceAnalytics/R/table.CaptureRatios.R 2014-02-23 12:51:48 UTC (rev 3332) @@ -9,7 +9,6 @@ #' \code{table.UpDownRatios} shows three: the capture ratio, the number ratio, #' and the percentage ratio. #' -#' @aliases table.CaptureRatios table.UpDownRatios #' @param Ra a vector of returns to test, e.g., the asset to be examined #' @param Rb a matrix, data.frame, or timeSeries of benchmark(s) to test the #' asset against. @@ -28,6 +27,8 @@ #' textplot(result, rmar = 0.8, cmar = 1.5, max.cex=.9, halign = "center", valign = "top", row.valign="center", wrap.rownames=15, wrap.colnames=10, mar = c(0,0,3,0)+0.1) #' title(main="Capture Ratios for EDHEC LS EQ") #' +#' @aliases table.CaptureRatios table.UpDownRatios +#' #' @export table.CaptureRatios <- function (Ra, Rb, digits = 4) Modified: pkg/PerformanceAnalytics/R/table.UpDownRatios.R =================================================================== --- pkg/PerformanceAnalytics/R/table.UpDownRatios.R 2014-02-22 03:32:41 UTC (rev 3331) +++ pkg/PerformanceAnalytics/R/table.UpDownRatios.R 2014-02-23 12:51:48 UTC (rev 3332) @@ -1,3 +1,5 @@ +#' @rdname table.CaptureRatios +#' @export table.UpDownRatios <- function (Ra, Rb, digits = 4) {# @author Peter Carl Modified: pkg/PerformanceAnalytics/man/ActivePremium.Rd =================================================================== --- pkg/PerformanceAnalytics/man/ActivePremium.Rd 2014-02-22 03:32:41 UTC (rev 3331) +++ pkg/PerformanceAnalytics/man/ActivePremium.Rd 2014-02-23 12:51:48 UTC (rev 3332) @@ -3,7 +3,7 @@ \alias{ActiveReturn} \title{Active Premium or Active Return} \usage{ - ActiveReturn(Ra, Rb, scale = NA) +ActiveReturn(Ra, Rb, scale = NA) } \arguments{ \item{Ra}{return vector of the portfolio} @@ -14,14 +14,14 @@ 252, monthly scale = 12, quarterly scale = 4)} } \description{ - The return on an investment's annualized return minus the - benchmark's annualized return. +The return on an investment's annualized return minus the +benchmark's annualized return. } \details{ - Active Premium = Investment's annualized return - - Benchmark's annualized return +Active Premium = Investment's annualized return - +Benchmark's annualized return - Also commonly referred to as 'active return'. +Also commonly referred to as 'active return'. } \examples{ data(managers) @@ -31,16 +31,15 @@ ActivePremium(managers[,1:6], managers[,8:7,drop=FALSE]) } \author{ - Peter Carl +Peter Carl } \references{ - Sharpe, W.F. The Sharpe Ratio,\emph{Journal of Portfolio - Management},Fall 1994, 49-58. +Sharpe, W.F. The Sharpe Ratio,\emph{Journal of Portfolio +Management},Fall 1994, 49-58. } \seealso{ - \code{\link{InformationRatio}} - \code{\link{TrackingError}} - \code{\link{Return.annualized}} +\code{\link{InformationRatio}} \code{\link{TrackingError}} +\code{\link{Return.annualized}} } \keyword{distribution} \keyword{models} Modified: pkg/PerformanceAnalytics/man/AdjustedSharpeRatio.Rd =================================================================== --- pkg/PerformanceAnalytics/man/AdjustedSharpeRatio.Rd 2014-02-22 03:32:41 UTC (rev 3331) +++ pkg/PerformanceAnalytics/man/AdjustedSharpeRatio.Rd 2014-02-23 12:51:48 UTC (rev 3332) @@ -2,7 +2,7 @@ \alias{AdjustedSharpeRatio} \title{Adjusted Sharpe ratio of the return distribution} \usage{ - AdjustedSharpeRatio(R, Rf = 0, ...) +AdjustedSharpeRatio(R, Rf = 0, ...) } \arguments{ \item{R}{an xts, vector, matrix, data frame, timeSeries @@ -13,18 +13,18 @@ \item{\dots}{any other passthru parameters} } \description{ - Adjusted Sharpe ratio was introduced by Pezier and White - (2006) to adjusts for skewness and kurtosis by - incorporating a penalty factor for negative skewness and - excess kurtosis. +Adjusted Sharpe ratio was introduced by Pezier and White +(2006) to adjusts for skewness and kurtosis by +incorporating a penalty factor for negative skewness and +excess kurtosis. } \details{ - \deqn{Adjusted Sharpe Ratio = SR * [1 + (\frac{S}{6}) * - SR - (\frac{K - 3}{24}) * SR^2]}{Adjusted Sharpe ratio = - SR x [1 + (S/6) x SR - ((K-3) / 24) x SR^2]} +\deqn{Adjusted Sharpe Ratio = SR * [1 + (\frac{S}{6}) * SR +- (\frac{K - 3}{24}) * SR^2]}{Adjusted Sharpe ratio = SR x +[1 + (S/6) x SR - ((K-3) / 24) x SR^2]} - where \eqn{SR} is the sharpe ratio with data annualized, - \eqn{S} is the skewness and \eqn{K} is the kurtosis +where \eqn{SR} is the sharpe ratio with data annualized, +\eqn{S} is the skewness and \eqn{K} is the kurtosis } \examples{ data(portfolio_bacon) @@ -35,11 +35,11 @@ print(AdjustedSharpeRatio(managers['1996',1])) } \author{ - Matthieu Lestel +Matthieu Lestel } \references{ - Carl Bacon, \emph{Practical portfolio performance - measurement and attribution}, second edition 2008 p.99 +Carl Bacon, \emph{Practical portfolio performance +measurement and attribution}, second edition 2008 p.99 } \keyword{distribution} \keyword{models} Modified: pkg/PerformanceAnalytics/man/AppraisalRatio.Rd =================================================================== --- pkg/PerformanceAnalytics/man/AppraisalRatio.Rd 2014-02-22 03:32:41 UTC (rev 3331) +++ pkg/PerformanceAnalytics/man/AppraisalRatio.Rd 2014-02-23 12:51:48 UTC (rev 3332) @@ -2,9 +2,8 @@ \alias{AppraisalRatio} \title{Appraisal ratio of the return distribution} \usage{ - AppraisalRatio(Ra, Rb, Rf = 0, - method = c("appraisal", "modified", "alternative"), - ...) +AppraisalRatio(Ra, Rb, Rf = 0, method = c("appraisal", "modified", + "alternative"), ...) } \arguments{ \item{Ra}{an xts, vector, matrix, data frame, timeSeries @@ -22,32 +21,31 @@ \item{\dots}{any other passthru parameters} } \description{ - Appraisal ratio is the Jensen's alpha adjusted for - specific risk. The numerator is divided by specific risk - instead of total risk. +Appraisal ratio is the Jensen's alpha adjusted for specific +risk. The numerator is divided by specific risk instead of +total risk. } \details{ - Modified Jensen's alpha is Jensen's alpha divided by - beta. +Modified Jensen's alpha is Jensen's alpha divided by beta. - Alternative Jensen's alpha is Jensen's alpha divided by - systematic risk. +Alternative Jensen's alpha is Jensen's alpha divided by +systematic risk. - \deqn{Appraisal ratio = - \frac{\alpha}{\sigma_{\epsilon}}}{Appraisal ratio = - Jensen's alpha / specific risk} +\deqn{Appraisal ratio = +\frac{\alpha}{\sigma_{\epsilon}}}{Appraisal ratio = +Jensen's alpha / specific risk} - \deqn{Modified Jensen's alpha = - \frac{\alpha}{\beta}}{Modified Jensen's alpha = Jensen's - alpha / beta} +\deqn{Modified Jensen's alpha = +\frac{\alpha}{\beta}}{Modified Jensen's alpha = Jensen's +alpha / beta} - \deqn{Alternative Jensen's alpha = - \frac{\alpha}{\sigma_S}}{Alternative Jensen's alpha = - Jensen's alpha / systematic risk} +\deqn{Alternative Jensen's alpha = +\frac{\alpha}{\sigma_S}}{Alternative Jensen's alpha = +Jensen's alpha / systematic risk} - where \eqn{alpha} is the Jensen's alpha, - \eqn{\sigma_{epsilon}} is the specific risk, - \eqn{\sigma_S} is the systematic risk. +where \eqn{alpha} is the Jensen's alpha, +\eqn{\sigma_{epsilon}} is the specific risk, \eqn{\sigma_S} +is the systematic risk. } \examples{ data(portfolio_bacon) @@ -60,11 +58,11 @@ print(AppraisalRatio(managers['1996',1:5], managers['1996',8])) } \author{ - Matthieu Lestel +Matthieu Lestel } \references{ - Carl Bacon, \emph{Practical portfolio performance - measurement and attribution}, second edition 2008 p.77 +Carl Bacon, \emph{Practical portfolio performance +measurement and attribution}, second edition 2008 p.77 } \keyword{distribution} \keyword{models} Modified: pkg/PerformanceAnalytics/man/AverageDrawdown.Rd =================================================================== --- pkg/PerformanceAnalytics/man/AverageDrawdown.Rd 2014-02-22 03:32:41 UTC (rev 3331) +++ pkg/PerformanceAnalytics/man/AverageDrawdown.Rd 2014-02-23 12:51:48 UTC (rev 3332) @@ -3,9 +3,9 @@ \alias{AverageRecovery} \title{Calculates the average of the observed drawdowns.} \usage{ - AverageDrawdown(R, ...) +AverageDrawdown(R, ...) - AverageRecovery(R, ...) +AverageRecovery(R, ...) } \arguments{ \item{R}{an xts, vector, matrix, data frame, timeSeries @@ -14,8 +14,8 @@ \item{\dots}{any other passthru parameters} } \description{ - ADD = abs(sum[j=1,2,...,d](D_j/d)) where D'_j = jth - drawdown over entire period d = total number of drawdowns - in the entire period +ADD = abs(sum[j=1,2,...,d](D_j/d)) where D'_j = jth +drawdown over entire period d = total number of drawdowns +in the entire period } Modified: pkg/PerformanceAnalytics/man/BernardoLedoitRatio.Rd =================================================================== --- pkg/PerformanceAnalytics/man/BernardoLedoitRatio.Rd 2014-02-22 03:32:41 UTC (rev 3331) +++ pkg/PerformanceAnalytics/man/BernardoLedoitRatio.Rd 2014-02-23 12:51:48 UTC (rev 3332) @@ -2,7 +2,7 @@ \alias{BernardoLedoitRatio} \title{Bernardo and Ledoit ratio of the return distribution} \usage{ - BernardoLedoitRatio(R, ...) +BernardoLedoitRatio(R, ...) } \arguments{ \item{R}{an xts, vector, matrix, data frame, timeSeries @@ -11,19 +11,19 @@ \item{\dots}{any other passthru parameters} } \description{ - To calculate Bernardo and Ledoit ratio we take the sum of - the subset of returns that are above 0 and we divide it - by the opposite of the sum of the subset of returns that - are below 0 +To calculate Bernardo and Ledoit ratio we take the sum of +the subset of returns that are above 0 and we divide it by +the opposite of the sum of the subset of returns that are +below 0 } \details{ - \deqn{BernardoLedoitRatio(R) = - \frac{\frac{1}{n}\sum^{n}_{t=1}{max(R_{t},0)}}{\frac{1}{n}\sum^{n}_{t=1}{max(-R_{t},0)}}}{BernardoLedoitRatio(R) - = 1/n*sum(t=1..n)(max(R(t),0)) / - 1/n*sum(t=1..n)(max(-R(t),0))} +\deqn{BernardoLedoitRatio(R) = +\frac{\frac{1}{n}\sum^{n}_{t=1}{max(R_{t},0)}}{\frac{1}{n}\sum^{n}_{t=1}{max(-R_{t},0)}}}{BernardoLedoitRatio(R) += 1/n*sum(t=1..n)(max(R(t),0)) / +1/n*sum(t=1..n)(max(-R(t),0))} - where \eqn{n} is the number of observations of the entire - series +where \eqn{n} is the number of observations of the entire +series } \examples{ data(portfolio_bacon) @@ -34,11 +34,11 @@ print(BernardoLedoitRatio(managers['1996',1])) #expected 4.598 } \author{ - Matthieu Lestel +Matthieu Lestel } \references{ - Carl Bacon, \emph{Practical portfolio performance - measurement and attribution}, second edition 2008 p.95 +Carl Bacon, \emph{Practical portfolio performance +measurement and attribution}, second edition 2008 p.95 } \keyword{distribution} \keyword{models} Modified: pkg/PerformanceAnalytics/man/BetaCoMoments.Rd =================================================================== --- pkg/PerformanceAnalytics/man/BetaCoMoments.Rd 2014-02-22 03:32:41 UTC (rev 3331) +++ pkg/PerformanceAnalytics/man/BetaCoMoments.Rd 2014-02-23 12:51:48 UTC (rev 3332) @@ -3,15 +3,13 @@ \alias{BetaCoMoments} \alias{BetaCoSkewness} \alias{BetaCoVariance} -\alias{SystematicKurtosis} -\alias{SystematicSkewness} \title{Functions to calculate systematic or beta co-moments of return series} \usage{ - BetaCoVariance(Ra, Rb) +BetaCoVariance(Ra, Rb) - BetaCoSkewness(Ra, Rb, test = FALSE) +BetaCoSkewness(Ra, Rb, test = FALSE) - BetaCoKurtosis(Ra, Rb) +BetaCoKurtosis(Ra, Rb) } \arguments{ \item{Ra}{an xts, vector, matrix, data frame, timeSeries @@ -24,8 +22,8 @@ \item{test}{condition not implemented yet} } \description{ - calculate higher co-moment betas, or 'systematic' - variance, skewness, and kurtosis +calculate higher co-moment betas, or 'systematic' variance, +skewness, and kurtosis } \examples{ data(managers) @@ -37,112 +35,109 @@ BetaCoKurtosis(managers[,1:6], managers[,8:7]) } \author{ - Kris Boudt, Peter Carl, Brian Peterson +Kris Boudt, Peter Carl, Brian Peterson } \references{ - Boudt, Kris, Brian G. Peterson, and Christophe Croux. - 2008. Estimation and Decomposition of Downside Risk for - Portfolios with Non-Normal Returns. Journal of Risk. - Winter. +Boudt, Kris, Brian G. Peterson, and Christophe Croux. 2008. +Estimation and Decomposition of Downside Risk for +Portfolios with Non-Normal Returns. Journal of Risk. +Winter. - Martellini, Lionel, and Volker Ziemann. 2007. Improved - Forecasts of Higher-Order Comoments and Implications for - Portfolio Selection. EDHEC Risk and Asset Management - Research Centre working paper. +Martellini, Lionel, and Volker Ziemann. 2007. Improved +Forecasts of Higher-Order Comoments and Implications for +Portfolio Selection. EDHEC Risk and Asset Management +Research Centre working paper. } \seealso{ - \code{\link{CoMoments}} +\code{\link{CoMoments}} } \concept{ - beta co-moments +beta co-moments - moments +moments - The co-moments, including covariance, coskewness, and - cokurtosis, do not allow the marginal impact of an asset - on a portfolio to be directly measured. Instead, - Martellini and Zieman (2007) develop a framework that - assesses the potential diversification of an asset - relative to a portfolio. They use higher moment betas to - estimate how much portfolio risk will be impacted by - adding an asset, in terms of symmetric risk (i.e., - volatility), in asymmetry risk (i.e., skewness), and - extreme risks (i.e. kurtosis). That allows them to show - that adding an asset to a portfolio (or benchmark) will - reduce the portfolio's variance to be reduced if the - second-order beta of the asset with respect to the - portfolio is less than one. They develop the same - concepts for the third and fourth order moments. The - authors offer these higher moment betas as a measure of - the diversification potential of an asset. +The co-moments, including covariance, coskewness, and +cokurtosis, do not allow the marginal impact of an asset on +a portfolio to be directly measured. Instead, Martellini +and Zieman (2007) develop a framework that assesses the +potential diversification of an asset relative to a +portfolio. They use higher moment betas to estimate how +much portfolio risk will be impacted by adding an asset, in +terms of symmetric risk (i.e., volatility), in asymmetry +risk (i.e., skewness), and extreme risks (i.e. kurtosis). +That allows them to show that adding an asset to a +portfolio (or benchmark) will reduce the portfolio's +variance to be reduced if the second-order beta of the +asset with respect to the portfolio is less than one. They +develop the same concepts for the third and fourth order +moments. The authors offer these higher moment betas as a +measure of the diversification potential of an asset. - Higher moment betas are defined as proportional to the - derivative of the covariance, coskewness and cokurtosis - of the second, third and fourth portfolio moment with - respect to the portfolio weights. The beta co-variance is - calculated as: +Higher moment betas are defined as proportional to the +derivative of the covariance, coskewness and cokurtosis of +the second, third and fourth portfolio moment with respect +to the portfolio weights. The beta co-variance is +calculated as: - \deqn{ BetaCoV(Ra,Rb) = \beta^{(2)}_{a,b} = - \frac{CoV(R_a,R_b)}{\mu^{(2)}(R_b)} }{BetaCoV(Ra,Rb) = - CoV(Ra,Rb)/centeredmoment(Rb,2)} +\deqn{ BetaCoV(Ra,Rb) = \beta^{(2)}_{a,b} = +\frac{CoV(R_a,R_b)}{\mu^{(2)}(R_b)} }{BetaCoV(Ra,Rb) = +CoV(Ra,Rb)/centeredmoment(Rb,2)} - Beta co-skewness is given as: +Beta co-skewness is given as: - \deqn{ BetaCoS(Ra,Rb) = \beta^{(3)}_{a,b}= - \frac{CoS(R_a,R_b)}{\mu^{(3)}(R_b)} }{BetaCoS(Ra,Rb) = - CoS(Ra,Rb)/centeredmoment(Rb,3)} +\deqn{ BetaCoS(Ra,Rb) = \beta^{(3)}_{a,b}= +\frac{CoS(R_a,R_b)}{\mu^{(3)}(R_b)} }{BetaCoS(Ra,Rb) = +CoS(Ra,Rb)/centeredmoment(Rb,3)} - Beta co-kurtosis is: +Beta co-kurtosis is: - \deqn{ BetaCoK(Ra,Rb)=\beta^{(4)}_{a,b} = - \frac{CoK(R_a,R_b)}{\mu^{(4)}(R_b)} }{BetaCoK(Ra,Rb) = - CoK(Ra,Rb)/centeredmoment(Rb,4)} +\deqn{ BetaCoK(Ra,Rb)=\beta^{(4)}_{a,b} = +\frac{CoK(R_a,R_b)}{\mu^{(4)}(R_b)} }{BetaCoK(Ra,Rb) = +CoK(Ra,Rb)/centeredmoment(Rb,4)} - where the \eqn{n}-th centered moment is calculated as +where the \eqn{n}-th centered moment is calculated as - \deqn{ \mu^{(n)}(R) = E\lbrack(R-E(R))^n\rbrack - }{moment^n(R) = E[R-E(R)^n]} +\deqn{ \mu^{(n)}(R) = E\lbrack(R-E(R))^n\rbrack +}{moment^n(R) = E[R-E(R)^n]} - A beta is greater than one indicates that no - diversification benefits should be expected from the - introduction of that asset into the portfolio. - Conversely, a beta that is less than one indicates that - adding the new asset should reduce the resulting - portfolio's volatility and kurtosis, and to an increase - in skewness. More specifically, the lower the beta the - higher the diversification effect on normal risk (i.e. - volatility). Similarly, since extreme risks are generally - characterised by negative skewness and positive kurtosis, - the lower the beta, the higher the diversification effect - on extreme risks (as reflected in Modified Value-at-Risk - or ER). +A beta is greater than one indicates that no +diversification benefits should be expected from the +introduction of that asset into the portfolio. Conversely, +a beta that is less than one indicates that adding the new +asset should reduce the resulting portfolio's volatility +and kurtosis, and to an increase in skewness. More +specifically, the lower the beta the higher the +diversification effect on normal risk (i.e. volatility). +Similarly, since extreme risks are generally characterised +by negative skewness and positive kurtosis, the lower the +beta, the higher the diversification effect on extreme +risks (as reflected in Modified Value-at-Risk or ER). - The addition of a small fraction of a new asset to a - portfolio leads to a decrease in the portfolio's second - moment (respectively, an increase in the portfolio's - third moment and a decrease in the portfolio's fourth - moment) if and only if the second moment (respectively, - the third moment and fourth moment) beta is less than one - (see Martellini and Ziemann (2007) for more details). +The addition of a small fraction of a new asset to a +portfolio leads to a decrease in the portfolio's second +moment (respectively, an increase in the portfolio's third +moment and a decrease in the portfolio's fourth moment) if +and only if the second moment (respectively, the third +moment and fourth moment) beta is less than one (see +Martellini and Ziemann (2007) for more details). - For skewness, the interpretation is slightly more - involved. If the skewness of the portfolio is negative, - we would expect an increase in portfolio skewness when - the third moment beta is lower than one. When the - skewness of the portfolio is positive, then the condition - is that the third moment beta is greater than, as opposed - to lower than, one. +For skewness, the interpretation is slightly more involved. +If the skewness of the portfolio is negative, we would +expect an increase in portfolio skewness when the third +moment beta is lower than one. When the skewness of the +portfolio is positive, then the condition is that the third +moment beta is greater than, as opposed to lower than, one. - %Because the interpretation of beta coskewness is made - difficult by the need to condition on it's skewness, we - deviate from the more widely used measure slightly. To - make the interpretation consistent across all three - measures, the beta coskewness function tests the skewness - and multiplies the result by the sign of the skewness. - That allows an analyst to review the metric and interpret - it without needing additional information. To use the - more widely used metric, simply set the parameter - \code{test = FALSE}. +%Because the interpretation of beta coskewness is made +difficult by the need to condition on it's skewness, we +deviate from the more widely used measure slightly. To +make the interpretation consistent across all three +measures, the beta coskewness function tests the skewness +and multiplies the result by the sign of the skewness. +That allows an analyst to review the metric and interpret +it without needing additional information. To use the more +widely used metric, simply set the parameter \code{test = +FALSE}. } \keyword{distribution} \keyword{models} Modified: pkg/PerformanceAnalytics/man/BurkeRatio.Rd =================================================================== --- pkg/PerformanceAnalytics/man/BurkeRatio.Rd 2014-02-22 03:32:41 UTC (rev 3331) +++ pkg/PerformanceAnalytics/man/BurkeRatio.Rd 2014-02-23 12:51:48 UTC (rev 3332) @@ -2,7 +2,7 @@ \alias{BurkeRatio} \title{Burke ratio of the return distribution} \usage{ - BurkeRatio(R, Rf = 0, modified = FALSE, ...) +BurkeRatio(R, Rf = 0, modified = FALSE, ...) } \arguments{ \item{R}{an xts, vector, matrix, data frame, timeSeries @@ -16,26 +16,25 @@ \item{\dots}{any other passthru parameters} } \description{ - To calculate Burke ratio we take the difference between - the portfolio return and the risk free rate and we divide - it by the square root of the sum of the square of the - drawdowns. To calculate the modified Burke ratio we just - multiply the Burke ratio by the square root of the number - of datas. +To calculate Burke ratio we take the difference between the +portfolio return and the risk free rate and we divide it by +the square root of the sum of the square of the drawdowns. +To calculate the modified Burke ratio we just multiply the +Burke ratio by the square root of the number of datas. } \details{ - \deqn{Burke Ratio = \frac{r_P - - r_F}{\sqrt{\sum^{d}_{t=1}{D_t}^2}}}{Burke Ratio = (Rp - - Rf) / (sqrt(sum(t=1..n)(Dt^2)))} +\deqn{Burke Ratio = \frac{r_P - +r_F}{\sqrt{\sum^{d}_{t=1}{D_t}^2}}}{Burke Ratio = (Rp - Rf) +/ (sqrt(sum(t=1..n)(Dt^2)))} - \deqn{Modified Burke Ratio = \frac{r_P - - r_F}{\sqrt{\sum^{d}_{t=1}\frac{{D_t}^2}{n}}}}{Modified - Burke Ratio = (Rp - Rf) / (sqrt(sum(t=1..n)(Dt^2 / n)))} +\deqn{Modified Burke Ratio = \frac{r_P - +r_F}{\sqrt{\sum^{d}_{t=1}\frac{{D_t}^2}{n}}}}{Modified +Burke Ratio = (Rp - Rf) / (sqrt(sum(t=1..n)(Dt^2 / n)))} - where \eqn{n} is the number of observations of the entire - series, \eqn{d} is number of drawdowns, \eqn{r_P} is the - portfolio return, \eqn{r_F} is the risk free rate and - \eqn{D_t} the \eqn{t^{th}} drawdown. +where \eqn{n} is the number of observations of the entire +series, \eqn{d} is number of drawdowns, \eqn{r_P} is the +portfolio return, \eqn{r_F} is the risk free rate and +\eqn{D_t} the \eqn{t^{th}} drawdown. } \examples{ data(portfolio_bacon) @@ -49,11 +48,11 @@ print(BurkeRatio(managers['1996',1], modified = TRUE)) } \author{ - Matthieu Lestel +Matthieu Lestel } \references{ - Carl Bacon, \emph{Practical portfolio performance - measurement and attribution}, second edition 2008 p.90-91 +Carl Bacon, \emph{Practical portfolio performance +measurement and attribution}, second edition 2008 p.90-91 } \keyword{distribution} \keyword{models} Modified: pkg/PerformanceAnalytics/man/CAPM.RiskPremium.Rd =================================================================== --- pkg/PerformanceAnalytics/man/CAPM.RiskPremium.Rd 2014-02-22 03:32:41 UTC (rev 3331) +++ pkg/PerformanceAnalytics/man/CAPM.RiskPremium.Rd 2014-02-23 12:51:48 UTC (rev 3332) @@ -11,13 +11,13 @@ \alias{SFM.utils} \title{utility functions for single factor (CAPM) CML, SML, and RiskPremium} \usage{ - CAPM.CML.slope(Rb, Rf = 0) +CAPM.CML.slope(Rb, Rf = 0) - CAPM.CML(Ra, Rb, Rf = 0) +CAPM.CML(Ra, Rb, Rf = 0) - CAPM.RiskPremium(Ra, Rf = 0) +CAPM.RiskPremium(Ra, Rf = 0) - CAPM.SML.slope(Rb, Rf = 0) +CAPM.SML.slope(Rb, Rf = 0) } \arguments{ \item{Ra}{an xts, vector, matrix, data frame, timeSeries @@ -28,71 +28,69 @@ \item{Rf}{risk free rate, in same period as your returns} } \description{ - The Capital Asset Pricing Model, from which the popular - \code{\link{SharpeRatio}} is derived, is a theory of - market equilibrium. These utility functions provide - values for various measures proposed in the CAPM. +The Capital Asset Pricing Model, from which the popular +\code{\link{SharpeRatio}} is derived, is a theory of market +equilibrium. These utility functions provide values for +various measures proposed in the CAPM. } \details{ - At it's core, the CAPM is a single factor linear model. - In light of the general ustility and wide use of single - factor model, all functions in the CAPM suite will also - be available with SFM (single factor model) prefixes. +At it's core, the CAPM is a single factor linear model. In +light of the general ustility and wide use of single factor +model, all functions in the CAPM suite will also be +available with SFM (single factor model) prefixes. - The CAPM provides a justification for passive or index - investing by positing that assets that are not on the - efficient frontier will either rise or lower in price - until they are on the efficient frontier of the market - portfolio. +The CAPM provides a justification for passive or index +investing by positing that assets that are not on the +efficient frontier will either rise or lower in price until +they are on the efficient frontier of the market portfolio. - The CAPM Risk Premium on an investment is the measure of - how much the asset's performance differs from the risk - free rate. Negative Risk Premium generally indicates - that the investment is a bad investment, and the money - should be allocated to the risk free asset or to a - different asset with a higher risk premium. +The CAPM Risk Premium on an investment is the measure of +how much the asset's performance differs from the risk free +rate. Negative Risk Premium generally indicates that the +investment is a bad investment, and the money should be +allocated to the risk free asset or to a different asset +with a higher risk premium. - The Capital Market Line relates the excess expected - return on an efficient market portfolio to it's Risk. - The slope of the CML is the Sharpe Ratio for the market - portfolio. The Security Market line is constructed by - calculating the line of Risk Premium over - \code{\link{CAPM.beta}}. For the benchmark asset this - will be 1 over the risk premium of the benchmark asset. - The CML also describes the only path allowed by the CAPM - to a portfolio that outperforms the efficient frontier: - it describes the line of reward/risk that a leveraged - portfolio will occupy. So, according to CAPM, no - portfolio constructed of the same assets can lie above - the CML. +The Capital Market Line relates the excess expected return +on an efficient market portfolio to it's Risk. The slope +of the CML is the Sharpe Ratio for the market portfolio. +The Security Market line is constructed by calculating the +line of Risk Premium over \code{\link{CAPM.beta}}. For the +benchmark asset this will be 1 over the risk premium of the +benchmark asset. The CML also describes the only path +allowed by the CAPM to a portfolio that outperforms the +efficient frontier: it describes the line of reward/risk +that a leveraged portfolio will occupy. So, according to +CAPM, no portfolio constructed of the same assets can lie +above the CML. - Probably the most complete criticism of CAPM in actual - practice (as opposed to structural or theory critiques) - is that it posits a market equilibrium, but is most often - used only in a partial equilibrium setting, for example - by using the S\&P 500 as the benchmark asset. A better - method of using and testing the CAPM would be to use a - general equilibrium model that took global assets from - all asset classes into consideration. +Probably the most complete criticism of CAPM in actual +practice (as opposed to structural or theory critiques) is +that it posits a market equilibrium, but is most often used +only in a partial equilibrium setting, for example by using +the S\&P 500 as the benchmark asset. A better method of +using and testing the CAPM would be to use a general +equilibrium model that took global assets from all asset +classes into consideration. - Chapter 7 of Ruppert(2004) gives an extensive overview of - CAPM, its assumptions and deficiencies. +Chapter 7 of Ruppert(2004) gives an extensive overview of +CAPM, its assumptions and deficiencies. - \code{SFM.RiskPremium} is the premium returned to the - investor over the risk free asset +\code{SFM.RiskPremium} is the premium returned to the +investor over the risk free asset - \deqn{\overline{(R_{a}-R_{f})}}{mean(Ra-Rf=0)} +\deqn{\overline{(R_{a}-R_{f})}}{mean(Ra-Rf=0)} - \code{SFM.CML} calculates the expected return of the - asset against the benchmark Capital Market Line +\code{SFM.CML} calculates the expected return of the asset [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3332 From noreply at r-forge.r-project.org Sun Feb 23 17:21:50 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 23 Feb 2014 17:21:50 +0100 (CET) Subject: [Returnanalytics-commits] r3333 - in pkg/PerformanceAnalytics: . R man vignettes Message-ID: <20140223162150.8C373186AB2@r-forge.r-project.org> Author: braverock Date: 2014-02-23 17:21:50 +0100 (Sun, 23 Feb 2014) New Revision: 3333 Modified: pkg/PerformanceAnalytics/.Rbuildignore pkg/PerformanceAnalytics/DESCRIPTION pkg/PerformanceAnalytics/NAMESPACE pkg/PerformanceAnalytics/R/CAPM.dynamic.R pkg/PerformanceAnalytics/R/MSquaredExcess.R pkg/PerformanceAnalytics/R/MarketTiming.R pkg/PerformanceAnalytics/R/StdDev.annualized.R pkg/PerformanceAnalytics/R/TreynorRatio.R pkg/PerformanceAnalytics/R/chart.TimeSeries.R pkg/PerformanceAnalytics/R/charts.RollingPerformance.R pkg/PerformanceAnalytics/R/lpm.R pkg/PerformanceAnalytics/R/table.AnnualizedReturns.R pkg/PerformanceAnalytics/R/table.Arbitrary.R pkg/PerformanceAnalytics/R/table.Autocorrelation.R pkg/PerformanceAnalytics/R/table.CAPM.R pkg/PerformanceAnalytics/R/table.CalendarReturns.R pkg/PerformanceAnalytics/R/table.CaptureRatios.R pkg/PerformanceAnalytics/R/table.Correlation.R pkg/PerformanceAnalytics/R/table.DownsideRisk.R pkg/PerformanceAnalytics/R/table.Drawdowns.R pkg/PerformanceAnalytics/R/table.HigherMoments.R pkg/PerformanceAnalytics/R/table.MonthlyReturns.R pkg/PerformanceAnalytics/R/table.RollingPeriods.R pkg/PerformanceAnalytics/R/textplot.R pkg/PerformanceAnalytics/R/zzz.R pkg/PerformanceAnalytics/man/CAPM.dynamic.Rd pkg/PerformanceAnalytics/man/MSquaredExcess.Rd pkg/PerformanceAnalytics/man/MarketTiming.Rd pkg/PerformanceAnalytics/man/TreynorRatio.Rd pkg/PerformanceAnalytics/man/chart.TimeSeries.Rd pkg/PerformanceAnalytics/man/charts.RollingPerformance.Rd pkg/PerformanceAnalytics/man/table.AnnualizedReturns.Rd pkg/PerformanceAnalytics/man/table.Arbitrary.Rd pkg/PerformanceAnalytics/man/table.Autocorrelation.Rd pkg/PerformanceAnalytics/man/table.CAPM.Rd pkg/PerformanceAnalytics/man/table.CalendarReturns.Rd pkg/PerformanceAnalytics/man/table.CaptureRatios.Rd pkg/PerformanceAnalytics/man/table.Correlation.Rd pkg/PerformanceAnalytics/man/table.DownsideRisk.Rd pkg/PerformanceAnalytics/man/table.Drawdowns.Rd pkg/PerformanceAnalytics/man/table.HigherMoments.Rd pkg/PerformanceAnalytics/man/table.MonthlyReturns.Rd pkg/PerformanceAnalytics/man/table.RollingPeriods.Rd pkg/PerformanceAnalytics/man/textplot.Rd pkg/PerformanceAnalytics/vignettes/PA-Bacon.Rnw pkg/PerformanceAnalytics/vignettes/PA-charts.Rnw pkg/PerformanceAnalytics/vignettes/PerformanceAnalyticsChartsPresentation-Meielisalp-2007.Rnw pkg/PerformanceAnalytics/vignettes/PerformanceAnalyticsPresentation-UseR-2007.Rnw pkg/PerformanceAnalytics/vignettes/textplotPresentation-CRUG-2011.Rnw Log: - more fixes for R CMD check prior to CRAN release Modified: pkg/PerformanceAnalytics/.Rbuildignore =================================================================== --- pkg/PerformanceAnalytics/.Rbuildignore 2014-02-23 12:51:48 UTC (rev 3332) +++ pkg/PerformanceAnalytics/.Rbuildignore 2014-02-23 16:21:50 UTC (rev 3333) @@ -3,3 +3,4 @@ ChangeLog.1.0.0 ^.*\.Rproj$ ^\.Rproj\.user$ +codeblock.txt Modified: pkg/PerformanceAnalytics/DESCRIPTION =================================================================== --- pkg/PerformanceAnalytics/DESCRIPTION 2014-02-23 12:51:48 UTC (rev 3332) +++ pkg/PerformanceAnalytics/DESCRIPTION 2014-02-23 16:21:50 UTC (rev 3333) @@ -15,7 +15,7 @@ numbers of functions will work with P&L or price data where possible. Depends: - R (>= 2.14.0), + R (>= 3.0.0), zoo, xts (>= 0.8-9) Suggests: @@ -32,8 +32,7 @@ URL: http://r-forge.r-project.org/projects/returnanalytics/ Copyright: (c) 2004-2014 Contributors: Kris Boudt, Diethelm Wuertz, Eric Zivot, Matthieu Lestel -Thanks: A special thanks for additional contributions from +Thanks: A special thanks for additional contributions or patches from Stefan Albrecht, Khahn Nygyen, Jeff Ryan, Josh Ulrich, Sankalp Upadhyay, Tobias Verbeke, - H. Felix Wittmann, Ram Ahluwalia - + H. Felix Wittmann, Ram Ahluwalia, R. Douglas Martin Modified: pkg/PerformanceAnalytics/NAMESPACE =================================================================== --- pkg/PerformanceAnalytics/NAMESPACE 2014-02-23 12:51:48 UTC (rev 3332) +++ pkg/PerformanceAnalytics/NAMESPACE 2014-02-23 16:21:50 UTC (rev 3333) @@ -230,6 +230,7 @@ export(tol8qualitative) export(tol9qualitative) export(zerofill) +import(xts) importFrom(stats,sd) importFrom(utils,packageDescription) importFrom(zoo,rollapply) Modified: pkg/PerformanceAnalytics/R/CAPM.dynamic.R =================================================================== --- pkg/PerformanceAnalytics/R/CAPM.dynamic.R 2014-02-23 12:51:48 UTC (rev 3332) +++ pkg/PerformanceAnalytics/R/CAPM.dynamic.R 2014-02-23 16:21:50 UTC (rev 3333) @@ -48,10 +48,15 @@ #' @examples #' #' data(managers) -#' CAPM.dynamic(managers[,1,drop=FALSE], managers[,8,drop=FALSE], Rf=.035/12, Z=managers[, 9:10]) -#' CAPM.dynamic(managers[80:120,1:6], managers[80:120,7,drop=FALSE], Rf=managers[80:120,10,drop=FALSE], Z=managers[80:120, 9:10]) -#' CAPM.dynamic(managers[80:120,1:6], managers[80:120,8:7], managers[80:120,10,drop=FALSE], Z=managers[80:120, 9:10]) +#' CAPM.dynamic(managers[,1,drop=FALSE], managers[,8,drop=FALSE], +#' Rf=.035/12, Z=managers[, 9:10]) #' +#' CAPM.dynamic(managers[80:120,1:6], managers[80:120,7,drop=FALSE], +#' Rf=managers[80:120,10,drop=FALSE], Z=managers[80:120, 9:10]) +#' +#' CAPM.dynamic(managers[80:120,1:6], managers[80:120,8:7], +#' managers[80:120,10,drop=FALSE], Z=managers[80:120, 9:10]) +#' #' @rdname CAPM.dynamic #' @export CAPM.dynamic SFM.dynamic CAPM.dynamic <- SFM.dynamic <- function (Ra, Rb, Rf = 0, Z, lags = 1, ...) Modified: pkg/PerformanceAnalytics/R/MSquaredExcess.R =================================================================== --- pkg/PerformanceAnalytics/R/MSquaredExcess.R 2014-02-23 12:51:48 UTC (rev 3332) +++ pkg/PerformanceAnalytics/R/MSquaredExcess.R 2014-02-23 16:21:50 UTC (rev 3333) @@ -23,12 +23,13 @@ #' @examples #' #' data(portfolio_bacon) -#' print(MSquaredExcess(portfolio_bacon[,1], portfolio_bacon[,2])) #expected -0.00998 -#' print(MSquaredExcess(portfolio_bacon[,1], portfolio_bacon[,2], Method="arithmetic")) #expected -0.011 +#' MSquaredExcess(portfolio_bacon[,1], portfolio_bacon[,2]) #expected -0.00998 +#' +#' MSquaredExcess(portfolio_bacon[,1], portfolio_bacon[,2], Method="arithmetic") #expected -0.011 #' #' data(managers) -#' print(MSquaredExcess(managers['1996',1], managers['1996',8])) -#' print(MSquaredExcess(managers['1996',1:5], managers['1996',8])) +#' MSquaredExcess(managers['1996',1], managers['1996',8]) +#' MSquaredExcess(managers['1996',1:5], managers['1996',8]) #' #' @export MSquaredExcess <- Modified: pkg/PerformanceAnalytics/R/MarketTiming.R =================================================================== --- pkg/PerformanceAnalytics/R/MarketTiming.R 2014-02-23 12:51:48 UTC (rev 3332) +++ pkg/PerformanceAnalytics/R/MarketTiming.R 2014-02-23 16:21:50 UTC (rev 3333) @@ -1,96 +1,96 @@ -#' Market timing models -#' -#' Allows to estimate Treynor-Mazuy or Merton-Henriksson market timing model. -#' The Treynor-Mazuy model is essentially a quadratic extension of the basic -#' CAPM. It is estimated using a multiple regression. The second term in the -#' regression is the value of excess return squared. If the gamma coefficient -#' in the regression is positive, then the estimated equation describes a -#' convex upward-sloping regression "line". The quadratic regression is: -#' \deqn{R_{p}-R_{f}=\alpha+\beta (R_{b} - R_{f})+\gamma (R_{b}-R_{f})^2+ -#' \varepsilon_{p}}{Rp - Rf = alpha + beta(Rb -Rf) + gamma(Rb - Rf)^2 + -#' epsilonp} -#' \eqn{\gamma}{gamma} is a measure of the curvature of the regression line. -#' If \eqn{\gamma}{gamma} is positive, this would indicate that the manager's -#' investment strategy demonstrates market timing ability. -#' -#' The basic idea of the Merton-Henriksson test is to perform a multiple -#' regression in which the dependent variable (portfolio excess return and a -#' second variable that mimics the payoff to an option). This second variable -#' is zero when the market excess return is at or below zero and is 1 when it -#' is above zero: -#' \deqn{R_{p}-R_{f}=\alpha+\beta (R_{b}-R_{f})+\gamma D+\varepsilon_{p}}{Rp - -#' Rf = alpha + beta * (Rb - Rf) + gamma * D + epsilonp} -#' where all variables are familiar from the CAPM model, except for the -#' up-market return \eqn{D=max(0,R_{b}-R_{f})}{D = max(0, Rb - Rf)} and market -#' timing abilities \eqn{\gamma}{gamma} -#' @param Ra an xts, vector, matrix, data frame, timeSeries or zoo object of -#' the asset returns -#' @param Rb an xts, vector, matrix, data frame, timeSeries or zoo object of -#' the benchmark asset return -#' @param Rf risk free rate, in same period as your returns -#' @param method used to select between Treynor-Mazuy and Henriksson-Merton -#' models. May be any of: \itemize{ \item TM - Treynor-Mazuy model, -#' \item HM - Henriksson-Merton model} By default Treynor-Mazuy is selected -#' @param \dots any other passthrough parameters -#' @author Andrii Babii, Peter Carl -#' @seealso \code{\link{CAPM.beta}} -#' @references J. Christopherson, D. Carino, W. Ferson. \emph{Portfolio -#' Performance Measurement and Benchmarking}. 2009. McGraw-Hill, p. 127-133. -#' \cr J. L. Treynor and K. Mazuy, "Can Mutual Funds Outguess the Market?" -#' \emph{Harvard Business Review}, vol44, 1966, pp. 131-136 -#' \cr Roy D. Henriksson and Robert C. Merton, "On Market Timing and Investment -#' Performance. II. Statistical Procedures for Evaluating Forecast Skills," -#' \emph{Journal of Business}, vol.54, October 1981, pp.513-533 \cr -#' @examples -#' -#' data(managers) -#' MarketTiming(managers[,1,drop=FALSE], managers[,8,drop=FALSE], Rf=.035/12, method = "HM") -#' MarketTiming(managers[80:120,1:6], managers[80:120,7,drop=FALSE], managers[80:120,10,drop=FALSE]) -#' MarketTiming(managers[80:120,1:6], managers[80:120,8:7], managers[80:120,10,drop=FALSE], method = "TM") -#' -#' @export -MarketTiming <- function (Ra, Rb, Rf = 0, method = c("TM", "HM")) -{ # @author Andrii Babii, Peter Carl - - # FUNCTION - - Ra = checkData(Ra) - Rb = checkData(Rb) - if (!is.null(dim(Rf))) - Rf = checkData(Rf) - Ra.ncols = NCOL(Ra) - Rb.ncols = NCOL(Rb) - pairs = expand.grid(1:Ra.ncols, 1) - method = method[1] - xRa = Return.excess(Ra, Rf) - xRb = Return.excess(Rb, Rf) - - mt <- function (xRa, xRb) - { - switch(method, - "HM" = { S = xRb > 0 }, - "TM" = { S = xRb } - ) - R = merge(xRa, xRb, xRb*S) - R.df = as.data.frame(R) - model = lm(R.df[, 1] ~ 1 + ., data = R.df[, -1]) - return(coef(model)) - } - - result = apply(pairs, 1, FUN = function(n, xRa, xRb) - mt(xRa[, n[1]], xRb[, 1]), xRa = xRa, xRb = xRb) - result = t(result) - - if (ncol(Rb) > 1){ - for (i in 2:ncol(xRb)){ - res = apply(pairs, 1, FUN = function(n, xRa, xRb) - mt(xRa[, n[1]], xRb[, i]), xRa = xRa, xRb = xRb) - res = t(res) - result = rbind(result, res) - } - } - - rownames(result) = paste(rep(colnames(Ra), ncol(Rb)), "to", rep(colnames(Rb), each = ncol(Ra))) - colnames(result) = c("Alpha", "Beta", "Gamma") - return(result) +#' Market timing models +#' +#' Allows to estimate Treynor-Mazuy or Merton-Henriksson market timing model. +#' The Treynor-Mazuy model is essentially a quadratic extension of the basic +#' CAPM. It is estimated using a multiple regression. The second term in the +#' regression is the value of excess return squared. If the gamma coefficient +#' in the regression is positive, then the estimated equation describes a +#' convex upward-sloping regression "line". The quadratic regression is: +#' \deqn{R_{p}-R_{f}=\alpha+\beta (R_{b} - R_{f})+\gamma (R_{b}-R_{f})^2+ +#' \varepsilon_{p}}{Rp - Rf = alpha + beta(Rb -Rf) + gamma(Rb - Rf)^2 + +#' epsilonp} +#' \eqn{\gamma}{gamma} is a measure of the curvature of the regression line. +#' If \eqn{\gamma}{gamma} is positive, this would indicate that the manager's +#' investment strategy demonstrates market timing ability. +#' +#' The basic idea of the Merton-Henriksson test is to perform a multiple +#' regression in which the dependent variable (portfolio excess return and a +#' second variable that mimics the payoff to an option). This second variable +#' is zero when the market excess return is at or below zero and is 1 when it +#' is above zero: +#' \deqn{R_{p}-R_{f}=\alpha+\beta (R_{b}-R_{f})+\gamma D+\varepsilon_{p}}{Rp - +#' Rf = alpha + beta * (Rb - Rf) + gamma * D + epsilonp} +#' where all variables are familiar from the CAPM model, except for the +#' up-market return \eqn{D=max(0,R_{b}-R_{f})}{D = max(0, Rb - Rf)} and market +#' timing abilities \eqn{\gamma}{gamma} +#' @param Ra an xts, vector, matrix, data frame, timeSeries or zoo object of +#' the asset returns +#' @param Rb an xts, vector, matrix, data frame, timeSeries or zoo object of +#' the benchmark asset return +#' @param Rf risk free rate, in same period as your returns +#' @param method used to select between Treynor-Mazuy and Henriksson-Merton +#' models. May be any of: \itemize{ \item TM - Treynor-Mazuy model, +#' \item HM - Henriksson-Merton model} By default Treynor-Mazuy is selected +#' @param \dots any other passthrough parameters +#' @author Andrii Babii, Peter Carl +#' @seealso \code{\link{CAPM.beta}} +#' @references J. Christopherson, D. Carino, W. Ferson. \emph{Portfolio +#' Performance Measurement and Benchmarking}. 2009. McGraw-Hill, p. 127-133. +#' \cr J. L. Treynor and K. Mazuy, "Can Mutual Funds Outguess the Market?" +#' \emph{Harvard Business Review}, vol44, 1966, pp. 131-136 +#' \cr Roy D. Henriksson and Robert C. Merton, "On Market Timing and Investment +#' Performance. II. Statistical Procedures for Evaluating Forecast Skills," +#' \emph{Journal of Business}, vol.54, October 1981, pp.513-533 \cr +#' @examples +#' +#' data(managers) +#' MarketTiming(managers[,1], managers[,8], Rf=.035/12, method = "HM") +#' MarketTiming(managers[80:120,1:6], managers[80:120,7], managers[80:120,10]) +#' MarketTiming(managers[80:120,1:6], managers[80:120,8:7], managers[80:120,10], method = "TM") +#' +#' @export +MarketTiming <- function (Ra, Rb, Rf = 0, method = c("TM", "HM")) +{ # @author Andrii Babii, Peter Carl + + # FUNCTION + + Ra = checkData(Ra) + Rb = checkData(Rb) + if (!is.null(dim(Rf))) + Rf = checkData(Rf) + Ra.ncols = NCOL(Ra) + Rb.ncols = NCOL(Rb) + pairs = expand.grid(1:Ra.ncols, 1) + method = method[1] + xRa = Return.excess(Ra, Rf) + xRb = Return.excess(Rb, Rf) + + mt <- function (xRa, xRb) + { + switch(method, + "HM" = { S = xRb > 0 }, + "TM" = { S = xRb } + ) + R = merge(xRa, xRb, xRb*S) + R.df = as.data.frame(R) + model = lm(R.df[, 1] ~ 1 + ., data = R.df[, -1]) + return(coef(model)) + } + + result = apply(pairs, 1, FUN = function(n, xRa, xRb) + mt(xRa[, n[1]], xRb[, 1]), xRa = xRa, xRb = xRb) + result = t(result) + + if (ncol(Rb) > 1){ + for (i in 2:ncol(xRb)){ + res = apply(pairs, 1, FUN = function(n, xRa, xRb) + mt(xRa[, n[1]], xRb[, i]), xRa = xRa, xRb = xRb) + res = t(res) + result = rbind(result, res) + } + } + + rownames(result) = paste(rep(colnames(Ra), ncol(Rb)), "to", rep(colnames(Rb), each = ncol(Ra))) + colnames(result) = c("Alpha", "Beta", "Gamma") + return(result) } \ No newline at end of file Modified: pkg/PerformanceAnalytics/R/StdDev.annualized.R =================================================================== --- pkg/PerformanceAnalytics/R/StdDev.annualized.R 2014-02-23 12:51:48 UTC (rev 3332) +++ pkg/PerformanceAnalytics/R/StdDev.annualized.R 2014-02-23 16:21:50 UTC (rev 3333) @@ -45,7 +45,7 @@ #' sd.multiperiod(edhec[,6,drop=FALSE],scale=3) #' #' @export StdDev.annualized sd.annualized sd.multiperiod -#' @alias StdDev.annualized sd.annualized sd.multiperiod +#' @aliases StdDev.annualized sd.annualized sd.multiperiod #' @rdname StdDev.annualized StdDev.annualized <- sd.annualized <- sd.multiperiod <- function (x, scale = NA, ...) Modified: pkg/PerformanceAnalytics/R/TreynorRatio.R =================================================================== --- pkg/PerformanceAnalytics/R/TreynorRatio.R 2014-02-23 12:51:48 UTC (rev 3332) +++ pkg/PerformanceAnalytics/R/TreynorRatio.R 2014-02-23 16:21:50 UTC (rev 3333) @@ -30,12 +30,12 @@ #' #' data(portfolio_bacon) #' data(managers) -#' round(TreynorRatio(managers[,1,drop=FALSE], managers[,8,drop=FALSE], Rf=.035/12),4) -#' round(TreynorRatio(managers[,1,drop=FALSE], managers[,8,drop=FALSE], Rf = managers[,10,drop=FALSE]),4) -#' round(TreynorRatio(managers[,1:6], managers[,8,drop=FALSE], Rf=.035/12),4) -#' round(TreynorRatio(managers[,1:6], managers[,8,drop=FALSE], Rf = managers[,10,drop=FALSE]),4) -#' round(TreynorRatio(managers[,1:6], managers[,8:7,drop=FALSE], Rf=.035/12),4) -#' round(TreynorRatio(managers[,1:6], managers[,8:7,drop=FALSE], Rf = managers[,10,drop=FALSE]),4) +#' round(TreynorRatio(managers[,1], managers[,8], Rf=.035/12),4) +#' round(TreynorRatio(managers[,1], managers[,8], Rf = managers[,10]),4) +#' round(TreynorRatio(managers[,1:6], managers[,8], Rf=.035/12),4) +#' round(TreynorRatio(managers[,1:6], managers[,8], Rf = managers[,10]),4) +#' round(TreynorRatio(managers[,1:6], managers[,8:7], Rf=.035/12),4) +#' round(TreynorRatio(managers[,1:6], managers[,8:7], Rf = managers[,10]),4) #' #' print(TreynorRatio(portfolio_bacon[,1], portfolio_bacon[,2], modified = TRUE)) #expected 0.7975 #' Modified: pkg/PerformanceAnalytics/R/chart.TimeSeries.R =================================================================== --- pkg/PerformanceAnalytics/R/chart.TimeSeries.R 2014-02-23 12:51:48 UTC (rev 3332) +++ pkg/PerformanceAnalytics/R/chart.TimeSeries.R 2014-02-23 16:21:50 UTC (rev 3333) @@ -135,7 +135,13 @@ #' R=edhec[,"Funds of Funds",drop=FALSE] #' Return.cumulative = cumprod(1+R) - 1 #' chart.TimeSeries(Return.cumulative) -#' chart.TimeSeries(Return.cumulative, colorset = "darkblue", legend.loc = "bottomright", period.areas = cycles.dates, period.color = "lightblue", event.lines = risk.dates, event.labels = risk.labels, event.color = "red", lwd = 2) +#' chart.TimeSeries(Return.cumulative, colorset = "darkblue", +#' legend.loc = "bottomright", +#' period.areas = cycles.dates, +#' period.color = "lightblue", +#' event.lines = risk.dates, +#' event.labels = risk.labels, +#' event.color = "red", lwd = 2) #' #' @export chart.TimeSeries <- Modified: pkg/PerformanceAnalytics/R/charts.RollingPerformance.R =================================================================== --- pkg/PerformanceAnalytics/R/charts.RollingPerformance.R 2014-02-23 12:51:48 UTC (rev 3332) +++ pkg/PerformanceAnalytics/R/charts.RollingPerformance.R 2014-02-23 16:21:50 UTC (rev 3333) @@ -21,7 +21,11 @@ #' @examples #' #' data(managers) -#' charts.RollingPerformance(managers[,1:8], Rf=managers[,10,drop=FALSE], colorset=tim8equal, main="Rolling 12-Month Performance", legend.loc="topleft") +#' charts.RollingPerformance(managers[,1:8], +#' Rf=managers[,10,drop=FALSE], +#' colorset=tim8equal, +#' main="Rolling 12-Month Performance", +#' legend.loc="topleft") #' #' @export charts.RollingPerformance <- Modified: pkg/PerformanceAnalytics/R/lpm.R =================================================================== --- pkg/PerformanceAnalytics/R/lpm.R 2014-02-23 12:51:48 UTC (rev 3332) +++ pkg/PerformanceAnalytics/R/lpm.R 2014-02-23 16:21:50 UTC (rev 3333) @@ -19,35 +19,33 @@ #' @export lpm <- function(R,n=2,threshold=0,about_mean=FALSE){ + R <- checkData(R) if(about_mean==TRUE){ #Calculate Number of obs less than threshold - nb = nrow(x[x Author: braverock Date: 2014-02-23 17:47:32 +0100 (Sun, 23 Feb 2014) New Revision: 3334 Modified: pkg/PerformanceAnalytics/tests/Examples/PerformanceAnalytics-Ex.Rout.save Log: - commit updated example output Modified: pkg/PerformanceAnalytics/tests/Examples/PerformanceAnalytics-Ex.Rout.save =================================================================== --- pkg/PerformanceAnalytics/tests/Examples/PerformanceAnalytics-Ex.Rout.save 2014-02-23 16:21:50 UTC (rev 3333) +++ pkg/PerformanceAnalytics/tests/Examples/PerformanceAnalytics-Ex.Rout.save 2014-02-23 16:47:32 UTC (rev 3334) @@ -1,7 +1,6 @@ -R version 2.15.2 (2012-10-26) -- "Trick or Treat" -Copyright (C) 2012 The R Foundation for Statistical Computing -ISBN 3-900051-07-0 +R version 3.0.2 (2013-09-25) -- "Frisbee Sailing" +Copyright (C) 2013 The R Foundation for Statistical Computing Platform: x86_64-pc-linux-gnu (64-bit) R is free software and comes with ABSOLUTELY NO WARRANTY. @@ -26,7 +25,7 @@ Attaching package: ?zoo? -The following object(s) are masked from ?package:base?: +The following objects are masked from ?package:base?: as.Date, as.Date.numeric @@ -34,21 +33,21 @@ Attaching package: ?PerformanceAnalytics? -The following object(s) are masked from ?package:graphics?: +The following object is masked from ?package:graphics?: legend > -> assign(".oldSearch", search(), pos = 'CheckExEnv') +> base::assign(".oldSearch", base::search(), pos = 'CheckExEnv') > cleanEx() > nameEx("ActivePremium") > ### * ActivePremium > > flush(stderr()); flush(stdout()) > -> ### Name: ActivePremium -> ### Title: Active Premium -> ### Aliases: ActivePremium +> ### Name: ActiveReturn +> ### Title: Active Premium or Active Return +> ### Aliases: ActivePremium ActiveReturn > ### Keywords: distribution models multivariate ts > > ### ** Examples @@ -171,7 +170,6 @@ > ### Title: Functions to calculate systematic or beta co-moments of return > ### series > ### Aliases: BetaCoKurtosis BetaCoMoments BetaCoSkewness BetaCoVariance -> ### SystematicKurtosis SystematicSkewness > ### Keywords: distribution models multivariate ts > > ### ** Examples @@ -243,9 +241,11 @@ > flush(stderr()); flush(stdout()) > > ### Name: CAPM.CML.slope -> ### Title: utility functions for CAPM CML, SML, and RiskPremium +> ### Title: utility functions for single factor (CAPM) CML, SML, and +> ### RiskPremium > ### Aliases: CAPM.CML CAPM.CML.slope CAPM.RiskPremium CAPM.SML.slope -> ### CAPM.utils +> ### CAPM.utils SFM.CML SFM.CML.slope SFM.RiskPremium SFM.SML.slope +> ### SFM.utils > ### Keywords: distribution models multivariate ts > > ### ** Examples @@ -276,8 +276,8 @@ > flush(stderr()); flush(stdout()) > > ### Name: CAPM.alpha -> ### Title: calculate CAPM alpha -> ### Aliases: CAPM.alpha +> ### Title: calculate single factor model (CAPM) alpha +> ### Aliases: CAPM.alpha SFM.alpha > ### Keywords: distribution models multivariate ts > > ### ** Examples @@ -334,8 +334,8 @@ > flush(stderr()); flush(stdout()) > > ### Name: CAPM.beta -> ### Title: calculate CAPM beta -> ### Aliases: CAPM.beta CAPM.beta.bear CAPM.beta.bull TimingRatio +> ### Title: calculate single factor model (CAPM) beta +> ### Aliases: CAPM.beta CAPM.beta.bear CAPM.beta.bull SFM.beta TimingRatio > ### Keywords: distribution models multivariate ts > > ### ** Examples @@ -406,6 +406,94 @@ > > > cleanEx() +> nameEx("CAPM.dynamic") +> ### * CAPM.dynamic +> +> flush(stderr()); flush(stdout()) +> +> ### Name: CAPM.dynamic +> ### Title: Time-varying conditional single factor model beta +> ### Aliases: CAPM.dynamic SFM.dynamic +> +> ### ** Examples +> +> data(managers) +> CAPM.dynamic(managers[,1,drop=FALSE], managers[,8,drop=FALSE], ++ Rf=.035/12, Z=managers[, 9:10]) + Average alpha US 10Y TR alpha at t - 1 US 3m TR alpha at t - 1 +HAM1 to SP500 TR 0.0070965 -0.196351 0.1665381 + Average beta US 10Y TR beta at t - 1 US 3m TR beta at t - 1 +HAM1 to SP500 TR 0.3248015 3.493336 -63.74814 +> +> CAPM.dynamic(managers[80:120,1:6], managers[80:120,7,drop=FALSE], ++ Rf=managers[80:120,10,drop=FALSE], Z=managers[80:120, 9:10]) + Average alpha US 10Y TR alpha at t - 1 +HAM1 to EDHEC LS EQ -0.0001741347 -0.23890464 +HAM2 to EDHEC LS EQ -0.0027673634 -0.06632217 +HAM3 to EDHEC LS EQ 0.0062624783 -0.21733015 +HAM4 to EDHEC LS EQ -0.0033262023 0.16135997 +HAM5 to EDHEC LS EQ 0.0043380559 0.26882960 +HAM6 to EDHEC LS EQ -0.0053865004 0.05000616 + US 3m TR alpha at t - 1 Average beta +HAM1 to EDHEC LS EQ -0.4385012 1.1793098 +HAM2 to EDHEC LS EQ -4.0176982 0.7067390 +HAM3 to EDHEC LS EQ 7.6804829 0.4260623 +HAM4 to EDHEC LS EQ -0.2091890 1.6367609 +HAM5 to EDHEC LS EQ 3.8497148 1.2224547 +HAM6 to EDHEC LS EQ -3.0664314 1.6281908 + US 10Y TR beta at t - 1 US 3m TR beta at t - 1 +HAM1 to EDHEC LS EQ 3.861212 -51.01409 +HAM2 to EDHEC LS EQ 5.682080 171.16658 +HAM3 to EDHEC LS EQ 1.507916 -705.20354 +HAM4 to EDHEC LS EQ -7.622136 -565.85196 +HAM5 to EDHEC LS EQ 7.083956 39.70358 +HAM6 to EDHEC LS EQ -11.035136 343.52891 +> +> CAPM.dynamic(managers[80:120,1:6], managers[80:120,8:7], ++ managers[80:120,10,drop=FALSE], Z=managers[80:120, 9:10]) + Average alpha US 10Y TR alpha at t - 1 +HAM1 to SP500 TR 0.0036316941 -0.03538369 +HAM2 to SP500 TR 0.0016901086 -0.05484988 +HAM3 to SP500 TR 0.0072668556 -0.05978008 +HAM4 to SP500 TR -0.0015875926 0.41314240 +HAM5 to SP500 TR 0.0083363515 0.35300102 +HAM6 to SP500 TR 0.0012839717 0.03521033 +HAM1 to EDHEC LS EQ -0.0001741347 -0.23890464 +HAM2 to EDHEC LS EQ -0.0027673634 -0.06632217 +HAM3 to EDHEC LS EQ 0.0062624783 -0.21733015 +HAM4 to EDHEC LS EQ -0.0033262023 0.16135997 +HAM5 to EDHEC LS EQ 0.0043380559 0.26882960 +HAM6 to EDHEC LS EQ -0.0053865004 0.05000616 + US 3m TR alpha at t - 1 Average beta +HAM1 to SP500 TR 0.08506313 0.51861197 +HAM2 to SP500 TR -2.91835013 0.05157528 +HAM3 to SP500 TR 4.10231175 0.17720080 +HAM4 to SP500 TR -6.04090381 1.20562924 +HAM5 to SP500 TR 1.56695525 0.57212866 +HAM6 to SP500 TR -1.72313785 0.59611332 +HAM1 to EDHEC LS EQ -0.43850123 1.17930984 +HAM2 to EDHEC LS EQ -4.01769818 0.70673900 +HAM3 to EDHEC LS EQ 7.68048289 0.42606233 +HAM4 to EDHEC LS EQ -0.20918897 1.63676093 +HAM5 to EDHEC LS EQ 3.84971482 1.22245465 +HAM6 to EDHEC LS EQ -3.06643145 1.62819081 + US 10Y TR beta at t - 1 US 3m TR beta at t - 1 +HAM1 to SP500 TR -1.181057 -65.73676 +HAM2 to SP500 TR 2.075534 -23.79983 +HAM3 to SP500 TR 1.063350 -256.19346 +HAM4 to SP500 TR -1.812210 162.03456 +HAM5 to SP500 TR 4.277306 183.06200 +HAM6 to SP500 TR -5.106318 189.51371 +HAM1 to EDHEC LS EQ 3.861212 -51.01409 +HAM2 to EDHEC LS EQ 5.682080 171.16658 +HAM3 to EDHEC LS EQ 1.507916 -705.20354 +HAM4 to EDHEC LS EQ -7.622136 -565.85196 +HAM5 to EDHEC LS EQ 7.083956 39.70358 +HAM6 to EDHEC LS EQ -11.035136 343.52891 +> +> +> +> cleanEx() > nameEx("CAPM.epsilon") > ### * CAPM.epsilon > @@ -413,19 +501,19 @@ > > ### Name: CAPM.epsilon > ### Title: Regression epsilon of the return distribution -> ### Aliases: CAPM.epsilon epsilon Regression +> ### Aliases: CAPM.epsilon SFM.epsilon > ### Keywords: distribution models multivariate ts > > ### ** Examples > > data(portfolio_bacon) -> print(CAPM.epsilon(portfolio_bacon[,1], portfolio_bacon[,2])) #expected -0.013 +> print(SFM.epsilon(portfolio_bacon[,1], portfolio_bacon[,2])) #expected -0.013 [1] -0.01313932 > > data(managers) -> print(CAPM.epsilon(managers['1996',1], managers['1996',8])) +> print(SFM.epsilon(managers['1996',1], managers['1996',8])) [1] 0.07425366 -> print(CAPM.epsilon(managers['1996',1:5], managers['1996',8])) +> print(SFM.epsilon(managers['1996',1:5], managers['1996',8])) HAM1 HAM2 HAM3 HAM4 Regression epsilon (Risk free = 0) 0.07425366 0.5399193 0.2048063 0.05570592 HAM5 @@ -441,19 +529,19 @@ > > ### Name: CAPM.jensenAlpha > ### Title: Jensen's alpha of the return distribution -> ### Aliases: CAPM.jensenAlpha Jensen'sAlpha +> ### Aliases: CAPM.jensenAlpha SFM.jensenAlpha > ### Keywords: distribution models multivariate ts > > ### ** Examples > > data(portfolio_bacon) -> print(CAPM.jensenAlpha(portfolio_bacon[,1], portfolio_bacon[,2])) #expected -0.014 +> print(SFM.jensenAlpha(portfolio_bacon[,1], portfolio_bacon[,2])) #expected -0.014 [1] -0.01416944 > > data(managers) -> print(CAPM.jensenAlpha(managers['1996',1], managers['1996',8])) +> print(SFM.jensenAlpha(managers['1996',1], managers['1996',8])) [1] 0.08077871 -> print(CAPM.jensenAlpha(managers['1996',1:5], managers['1996',8])) +> print(SFM.jensenAlpha(managers['1996',1:5], managers['1996',8])) HAM1 HAM2 HAM3 HAM4 HAM5 Jensen's Alpha (Risk free = 0) 0.08077871 NA 0.2196026 0.06063837 NA > @@ -468,7 +556,7 @@ > ### Name: CDD > ### Title: Calculate Uryasev's proposed Conditional Drawdown at Risk (CDD > ### or CDaR) measure -> ### Aliases: CDaR CDD +> ### Aliases: CDD CDaR > ### Keywords: distribution models multivariate ts > > ### ** Examples @@ -590,11 +678,11 @@ > #with data used in Bacon 2008 > > data(portfolio_bacon) -> MAR = 0.5 -> DownsideDeviation(portfolio_bacon[,1], MAR) #expected 0.493 -[1] 0.492524 -> DownsidePotential(portfolio_bacon[,1], MAR) #expected 0.491 -[1] 0.491 +> MAR = 0.005 +> DownsideDeviation(portfolio_bacon[,1], MAR) #expected 0.0255 +[1] 0.02553674 +> DownsidePotential(portfolio_bacon[,1], MAR) #expected 0.0137 +[1] 0.01370833 > > #with data of managers > @@ -938,11 +1026,11 @@ > data(managers) > MAR = 0 > print(MSquaredExcess(managers['1996',1], managers['1996',8], MAR)) - HAM1 -HAM1 -0.127433 + SP500 TR +SP500 TR 0.02027322 > print(MSquaredExcess(managers['1996',1:5], managers['1996',8], MAR)) - HAM1 HAM2 HAM3 HAM4 HAM5 -MSquaredExcess (Risk free = 0) -0.127433 NA 0.1456129 -0.01310258 NA + HAM1 HAM2 HAM3 HAM4 HAM5 +MSquaredExcess (Risk free = 0) 0.02027322 NA 0.1409545 -0.02546609 NA > > > @@ -960,17 +1048,17 @@ > ### ** Examples > > data(portfolio_bacon) -> print(MSquared(portfolio_bacon[,1], portfolio_bacon[,2])) #expected 0.1068 - portfolio.monthly.return.... -portfolio.monthly.return.... 0.1068296 +> print(MSquared(portfolio_bacon[,1], portfolio_bacon[,2])) #expected 0.10062 + benchmark.return.... +benchmark.return.... 0.10062 > > data(managers) > print(MSquared(managers['1996',1], managers['1996',8])) - HAM1 -HAM1 0.07287385 + SP500 TR +SP500 TR 0.2544876 > print(MSquared(managers['1996',1:5], managers['1996',8])) - HAM1 HAM2 HAM3 HAM4 HAM5 -MSquared (Risk free = 0) 0.07287385 NA 0.4086003 0.21345 NA + HAM1 HAM2 HAM3 HAM4 HAM5 +MSquared (Risk free = 0) 0.2544876 NA 0.4028725 0.1982483 NA > > > @@ -988,24 +1076,66 @@ > ### ** Examples > > data(portfolio_bacon) -> print(MSquaredExcess(portfolio_bacon[,1], portfolio_bacon[,2])) #expected -0.00998 - portfolio.monthly.return.... -portfolio.monthly.return.... -0.009976721 -> print(MSquaredExcess(portfolio_bacon[,1], portfolio_bacon[,2], Method="arithmetic")) #expected -0.011 - portfolio.monthly.return.... -portfolio.monthly.return.... -0.01115381 +> MSquaredExcess(portfolio_bacon[,1], portfolio_bacon[,2]) #expected -0.00998 + benchmark.return.... +benchmark.return.... -0.01553103 > +> MSquaredExcess(portfolio_bacon[,1], portfolio_bacon[,2], Method="arithmetic") #expected -0.011 + benchmark.return.... +benchmark.return.... -0.01736344 +> > data(managers) -> print(MSquaredExcess(managers['1996',1], managers['1996',8])) - HAM1 -HAM1 -0.127433 -> print(MSquaredExcess(managers['1996',1:5], managers['1996',8])) - HAM1 HAM2 HAM3 HAM4 HAM5 -MSquaredExcess (Risk free = 0) -0.127433 NA 0.1456129 -0.01310258 NA +> MSquaredExcess(managers['1996',1], managers['1996',8]) + SP500 TR +SP500 TR 0.02027322 +> MSquaredExcess(managers['1996',1:5], managers['1996',8]) + HAM1 HAM2 HAM3 HAM4 HAM5 +MSquaredExcess (Risk free = 0) 0.02027322 NA 0.1409545 -0.02546609 NA > > > > cleanEx() +> nameEx("MarketTiming") +> ### * MarketTiming +> +> flush(stderr()); flush(stdout()) +> +> ### Name: MarketTiming +> ### Title: Market timing models +> ### Aliases: MarketTiming +> +> ### ** Examples +> +> data(managers) +> MarketTiming(managers[,1], managers[,8], Rf=.035/12, method = "HM") + Alpha Beta Gamma +HAM1 to SP500 TR 0.008275839 0.4555824 -0.1344417 +> MarketTiming(managers[80:120,1:6], managers[80:120,7], managers[80:120,10]) + Alpha Beta Gamma +HAM1 to EDHEC LS EQ -0.0005755802 1.3121058 -0.405150 +HAM2 to EDHEC LS EQ -0.0003616789 0.4370998 8.520620 +HAM3 to EDHEC LS EQ -0.0058148518 1.1898242 11.913786 +HAM4 to EDHEC LS EQ -0.0055113742 2.0616524 18.797340 +HAM5 to EDHEC LS EQ 0.0005125284 1.0703704 -5.077881 +HAM6 to EDHEC LS EQ 0.0003590925 1.2711094 -7.443428 +> MarketTiming(managers[80:120,1:6], managers[80:120,8:7], managers[80:120,10], method = "TM") + Alpha Beta Gamma +HAM1 to SP500 TR 0.0048833318 0.5970167 -0.2801650 +HAM2 to SP500 TR 0.0050694247 0.1190405 -0.5000263 +HAM3 to SP500 TR 0.0032110848 0.5272982 -0.6645684 +HAM4 to SP500 TR 0.0094634771 0.8779523 -0.8155100 +HAM5 to SP500 TR 0.0087234498 0.2869943 -2.7728051 +HAM6 to SP500 TR 0.0048031173 0.2902262 0.6910898 +HAM1 to EDHEC LS EQ -0.0005755802 1.3121058 -0.4051500 +HAM2 to EDHEC LS EQ -0.0003616789 0.4370998 8.5206196 +HAM3 to EDHEC LS EQ -0.0058148518 1.1898242 11.9137857 +HAM4 to EDHEC LS EQ -0.0055113742 2.0616524 18.7973395 +HAM5 to EDHEC LS EQ 0.0005125284 1.0703704 -5.0778814 +HAM6 to EDHEC LS EQ 0.0003590925 1.2711094 -7.4434281 +> +> +> +> cleanEx() > nameEx("MartinRatio") > ### * MartinRatio > @@ -1064,6 +1194,36 @@ > > > cleanEx() +> nameEx("Modigliani") +> ### * Modigliani +> +> flush(stderr()); flush(stdout()) +> +> ### Name: Modigliani +> ### Title: Modigliani-Modigliani measure +> ### Aliases: Modigliani +> +> ### ** Examples +> +> data(managers) +> Modigliani(managers[,1,drop=FALSE], managers[,8,drop=FALSE], Rf=.035/12) +[1] 0.01678381 +> Modigliani(managers[,1:6], managers[,8,drop=FALSE], managers[,8,drop=FALSE]) + HAM1 HAM2 HAM3 +Modigliani-Modigliani measure: SP500 TR 0.01281799 0.01505458 0.0131509 + HAM4 HAM5 HAM6 +Modigliani-Modigliani measure: SP500 TR 0.01057959 0.01053081 0.01844616 +> Modigliani(managers[,1:6], managers[,8:7], managers[,8,drop=FALSE]) + HAM1 HAM2 HAM3 +Modigliani-Modigliani measure: SP500 TR 0.01281799 0.01505458 0.01315090 +Modigliani-Modigliani measure: EDHEC LS EQ 0.01062640 0.01168261 0.01078361 + HAM4 HAM5 HAM6 +Modigliani-Modigliani measure: SP500 TR 0.01057959 0.010530812 0.01844616 +Modigliani-Modigliani measure: EDHEC LS EQ 0.00956933 0.009546295 0.01328426 +> +> +> +> cleanEx() > nameEx("NetSelectivity") > ### * NetSelectivity > @@ -1482,6 +1642,27 @@ > > > cleanEx() +> nameEx("Return.annualized.excess") +> ### * Return.annualized.excess +> +> flush(stderr()); flush(stdout()) +> +> ### Name: Return.annualized.excess +> ### Title: calculates an annualized excess return for comparing instruments +> ### with different length history +> ### Aliases: Return.annualized.excess +> ### Keywords: distribution models multivariate ts +> +> ### ** Examples +> +> data(managers) +> Return.annualized.excess(Rp = managers[,1], Rb = managers[,8]) + HAM1 +Annualized Return 0.03718883 +> +> +> +> cleanEx() > nameEx("Return.calculate") > ### * Return.calculate > @@ -1495,8 +1676,8 @@ > ### ** Examples > > ## Not run: -> ##D require(tseries) -> ##D prices = get.hist.quote("IBM", start = "1999-01-01", end = "2007-01-01", quote = "AdjClose", compression = "d") +> ##D require(quantmod) +> ##D prices = getSymbols("IBM", from = "1999-01-01", to = "2007-01-01") > ##D > ## End(Not run) > ## Don't show: @@ -4938,7 +5119,7 @@ > > ### Name: SkewnessKurtosisRatio > ### Title: Skewness-Kurtosis ratio of the return distribution -> ### Aliases: SkewnessKurtosisRatio Skewness-KurtosisRatio +> ### Aliases: Skewness-KurtosisRatio SkewnessKurtosisRatio > ### Keywords: distribution models multivariate ts > > ### ** Examples @@ -5101,14 +5282,28 @@ [1,] 0.01048561 $contribution - [1] 0.0008658123 0.0006049525 0.0010509579 0.0021479823 0.0004348643 - [6] 0.0011469074 0.0006822007 0.0010512230 0.0013150652 0.0005428396 -[11] 0.0007548481 -0.0013277224 0.0012156837 + Convertible Arbitrage CTA Global Distressed Securities + 0.0008658123 0.0006049525 0.0010509579 + Emerging Markets Equity Market Neutral Event Driven + 0.0021479823 0.0004348643 0.0011469074 +Fixed Income Arbitrage Global Macro Long/Short Equity + 0.0006822007 0.0010512230 0.0013150652 + Merger Arbitrage Relative Value Short Selling + 0.0005428396 0.0007548481 -0.0013277224 + Funds of Funds + 0.0012156837 $pct_contrib_StdDev - [1] 0.08257143 0.05769357 0.10022854 0.20485039 0.04147247 0.10937913 - [7] 0.06506063 0.10025383 0.12541613 0.05176994 0.07198892 -0.12662322 -[13] 0.11593824 + Convertible Arbitrage CTA Global Distressed Securities + 0.08257143 0.05769357 0.10022854 + Emerging Markets Equity Market Neutral Event Driven + 0.20485039 0.04147247 0.10937913 +Fixed Income Arbitrage Global Macro Long/Short Equity + 0.06506063 0.10025383 0.12541613 + Merger Arbitrage Relative Value Short Selling + 0.05176994 0.07198892 -0.12662322 + Funds of Funds + 0.11593824 > > @@ -5124,7 +5319,7 @@ > > ### Name: StdDev.annualized > ### Title: calculate a multiperiod or annualized Standard Deviation -> ### Aliases: sd.annualized sd.multiperiod StdDev.annualized +> ### Aliases: StdDev.annualized sd.annualized sd.multiperiod > ### Keywords: distribution models multivariate ts > > ### ** Examples @@ -5254,21 +5449,21 @@ > > data(portfolio_bacon) > data(managers) -> round(TreynorRatio(managers[,1,drop=FALSE], managers[,8,drop=FALSE], Rf=.035/12),4) +> round(TreynorRatio(managers[,1], managers[,8], Rf=.035/12),4) [1] 0.2528 -> round(TreynorRatio(managers[,1,drop=FALSE], managers[,8,drop=FALSE], Rf = managers[,10,drop=FALSE]),4) +> round(TreynorRatio(managers[,1], managers[,8], Rf = managers[,10]),4) [1] 0.2428 -> round(TreynorRatio(managers[,1:6], managers[,8,drop=FALSE], Rf=.035/12),4) +> round(TreynorRatio(managers[,1:6], managers[,8], Rf=.035/12),4) HAM1 HAM2 HAM3 HAM4 HAM5 HAM6 Treynor Ratio: SP500 TR 0.2528 0.3925 0.201 0.1209 0.0052 0.3042 -> round(TreynorRatio(managers[,1:6], managers[,8,drop=FALSE], Rf = managers[,10,drop=FALSE]),4) +> round(TreynorRatio(managers[,1:6], managers[,8], Rf = managers[,10]),4) HAM1 HAM2 HAM3 HAM4 HAM5 HAM6 Treynor Ratio: SP500 TR 0.2428 0.3883 0.1956 0.1144 0.0219 0.3401 -> round(TreynorRatio(managers[,1:6], managers[,8:7,drop=FALSE], Rf=.035/12),4) +> round(TreynorRatio(managers[,1:6], managers[,8:7], Rf=.035/12),4) HAM1 HAM2 HAM3 HAM4 HAM5 HAM6 Treynor Ratio: SP500 TR 0.2528 0.3925 0.2010 0.1209 0.0052 0.3042 Treynor Ratio: EDHEC LS EQ 0.1297 0.1088 0.0776 0.0504 0.0014 0.0966 -> round(TreynorRatio(managers[,1:6], managers[,8:7,drop=FALSE], Rf = managers[,10,drop=FALSE]),4) +> round(TreynorRatio(managers[,1:6], managers[,8:7], Rf = managers[,10]),4) HAM1 HAM2 HAM3 HAM4 HAM5 HAM6 Treynor Ratio: SP500 TR 0.2428 0.3883 0.1956 0.1144 0.0219 0.3401 Treynor Ratio: EDHEC LS EQ 0.1242 0.1068 0.0753 0.0471 0.0060 0.1086 @@ -5792,7 +5987,7 @@ > > ### Name: Return.centered > ### Title: calculate centered Returns -> ### Aliases: centeredcomoment centeredmoment Return.centered +> ### Aliases: Return.centered centeredcomoment centeredmoment > ### Keywords: distribution models multivariate ts > > ### ** Examples @@ -5941,7 +6136,7 @@ > > flush(stderr()); flush(stdout()) > -> ### Name: chart.ACFplus +> ### Name: chart.ACF > ### Title: Create ACF chart or ACF with PACF two-panel chart > ### Aliases: chart.ACF chart.ACFplus > ### Keywords: distribution hplot models multivariate ts @@ -6502,15 +6697,17 @@ > > ### ** Examples > -> data(managers) -> R = Drawdowns(managers[,2,drop=FALSE]) -> n = table.Drawdowns(managers[,2,drop=FALSE]) -> chart.Events(Drawdowns(managers[,2,drop=FALSE]), -+ dates = n$Trough, -+ prior=max(na.omit(n$"To Trough")), -+ post=max(na.omit(n$Recovery)), -+ lwd=2, colorset=redfocus, legend.loc=NULL, -+ main = "Worst Drawdowns") +> ## Not run: +> ##D data(managers) +> ##D R = PerformanceAnalytics:::Drawdowns(managers[,2,drop=FALSE]) +> ##D n = table.Drawdowns(managers[,2,drop=FALSE]) +> ##D chart.Events(PerformanceAnalytics:::Drawdowns(managers[,2,drop=FALSE]), +> ##D dates = n$Trough, +> ##D prior=max(na.omit(n$"To Trough")), +> ##D post=max(na.omit(n$Recovery)), +> ##D lwd=2, colorset=redfocus, legend.loc=NULL, +> ##D main = "Worst Drawdowns") +> ## End(Not run) > > > @@ -6672,16 +6869,6 @@ > data(edhec) > chart.RiskReturnScatter(edhec, Rf = .04/12) > chart.RiskReturnScatter(edhec, Rf = .04/12, add.boxplots = TRUE) -Warning in par(original.layout) : - graphical parameter "cin" cannot be set -Warning in par(original.layout) : - graphical parameter "cra" cannot be set -Warning in par(original.layout) : - graphical parameter "csi" cannot be set -Warning in par(original.layout) : - graphical parameter "cxy" cannot be set -Warning in par(original.layout) : - graphical parameter "din" cannot be set > > > @@ -6777,13 +6964,10 @@ > dev.new() > chart.RollingQuantileRegression(managers[, 1, drop=FALSE], + managers[, 8, drop=FALSE], Rf = .04/12) -Package SparseM (0.96) loaded. - To cite, see citation("SparseM") - Attaching package: ?SparseM? -The following object(s) are masked from ?package:base?: +The following object is masked from ?package:base?: backsolve @@ -6899,9 +7083,9 @@ > > flush(stderr()); flush(stdout()) > -> ### Name: charts.TimeSeries +> ### Name: chart.TimeSeries > ### Title: Creates a time series chart with some extensions. -> ### Aliases: charts.TimeSeries chart.TimeSeries +> ### Aliases: chart.TimeSeries charts.TimeSeries > ### Keywords: distribution hplot models multivariate ts > > ### ** Examples @@ -6964,7 +7148,13 @@ > R=edhec[,"Funds of Funds",drop=FALSE] > Return.cumulative = cumprod(1+R) - 1 > chart.TimeSeries(Return.cumulative) -> chart.TimeSeries(Return.cumulative, colorset = "darkblue", legend.loc = "bottomright", period.areas = cycles.dates, period.color = "lightblue", event.lines = risk.dates, event.labels = risk.labels, event.color = "red", lwd = 2) +> chart.TimeSeries(Return.cumulative, colorset = "darkblue", ++ legend.loc = "bottomright", ++ period.areas = cycles.dates, ++ period.color = "lightblue", ++ event.lines = risk.dates, ++ event.labels = risk.labels, ++ event.color = "red", lwd = 2) > > > @@ -7022,7 +7212,11 @@ > ### ** Examples > > data(managers) -> charts.RollingPerformance(managers[,1:8], Rf=managers[,10,drop=FALSE], colorset=tim8equal, main="Rolling 12-Month Performance", legend.loc="topleft") +> charts.RollingPerformance(managers[,1:8], ++ Rf=managers[,10,drop=FALSE], ++ colorset=tim8equal, ++ main="Rolling 12-Month Performance", ++ legend.loc="topleft") > > > @@ -7502,7 +7696,7 @@ > ### Name: mean.geometric > ### Title: calculate attributes relative to the mean of the observation > ### series given, including geometric, stderr, LCL and UCL -> ### Aliases: mean.geometric mean.LCL mean.stderr mean.UCL mean.utils +> ### Aliases: mean.LCL mean.UCL mean.geometric mean.stderr mean.utils > ### Keywords: distribution models multivariate ts > > ### ** Examples @@ -7734,37 +7928,45 @@ > > require("Hmisc") Loading required package: Hmisc +Loading required package: cluster +Loading required package: grid +Loading required package: lattice Loading required package: survival Loading required package: splines +Loading required package: Formula Hmisc library by Frank E Harrell Jr Type library(help='Hmisc'), ?Overview, or ?Hmisc.Overview') to see overall documentation. -NOTE:Hmisc no longer redefines [.factor to drop unused levels when -subsetting. To get the old behavior of Hmisc type dropUnusedLevels(). - Attaching package: ?Hmisc? -The following object(s) are masked from ?package:survival?: +The following objects are masked from ?package:survival?: - untangle.specials + survfitKM, untangle.specials -The following object(s) are masked from ?package:base?: +The following objects are masked from ?package:base?: format.pval, round.POSIXt, trunc.POSIXt, units > result = t(table.AnnualizedReturns(managers[,1:8], Rf=.04/12)) > -> textplot(format.df(result, na.blank=TRUE, numeric.dollar=FALSE, cdec=c(3,3,1)), rmar = 0.8, cmar = 2, max.cex=.9, halign = "center", valign = "top", row.valign="center", wrap.rownames=20, wrap.colnames=10, col.rownames=c("red", rep("darkgray",5), rep("orange",2)), mar = c(0,0,3,0)+0.1) +> textplot(format.df(result, na.blank=TRUE, numeric.dollar=FALSE, ++ cdec=c(3,3,1)), rmar = 0.8, cmar = 2, max.cex=.9, ++ halign = "center", valign = "top", row.valign="center", ++ wrap.rownames=20, wrap.colnames=10, col.rownames=c("red", ++ rep("darkgray",5), rep("orange",2)), mar = c(0,0,3,0)+0.1) +> > title(main="Annualized Performance") > > > > cleanEx() -detaching ?package:Hmisc?, ?package:survival?, ?package:splines? +detaching ?package:Hmisc?, ?package:Formula?, ?package:survival?, + ?package:splines?, ?package:lattice?, ?package:grid?, + ?package:cluster? > nameEx("table.Arbitrary") > ### * table.Arbitrary @@ -7780,7 +7982,8 @@ > ### ** Examples > > data(edhec) -> table.Arbitrary(edhec,metrics=c("VaR", "ES"),metricsNames=c("Modified VaR","Modified Expected Shortfall")) +> table.Arbitrary(edhec,metrics=c("VaR", "ES"), ++ metricsNames=c("Modified VaR","Modified Expected Shortfall")) Convertible Arbitrage CTA Global Modified VaR -0.03247395 -0.03380228 Modified Expected Shortfall -0.09954768 -0.04284185 @@ -7831,7 +8034,11 @@ US 3m TR 0.9224 0.9081 0.8968 0.8746 0.8363 0.8127 0.0000 > > result = t(table.Autocorrelation(managers[,1:8])) -> textplot(result, rmar = 0.8, cmar = 2, max.cex=.9, halign = "center", valign = "top", row.valign="center", wrap.rownames=15, wrap.colnames=10, mar = c(0,0,3,0)+0.1) +> +> textplot(result, rmar = 0.8, cmar = 2, max.cex=.9, halign = "center", ++ valign = "top", row.valign="center", wrap.rownames=15, ++ wrap.colnames=10, mar = c(0,0,3,0)+0.1) +> > title(main="Autocorrelation") > > @@ -7842,15 +8049,16 @@ > > flush(stderr()); flush(stdout()) > -> ### Name: table.CAPM -> ### Title: Asset-Pricing Model Summary: Statistics and Stylized Facts -> ### Aliases: table.CAPM +> ### Name: table.SFM +> ### Title: Single Factor Asset-Pricing Model Summary: Statistics and +> ### Stylized Facts +> ### Aliases: table.CAPM table.SFM > ### Keywords: distribution models multivariate ts > > ### ** Examples > > data(managers) -> table.CAPM(managers[,1:3,drop=FALSE], managers[,8,drop=FALSE], Rf = managers[,10,drop=FALSE]) +> table.SFM(managers[,1:3], managers[,8], Rf = managers[,10]) HAM1 to SP500 TR HAM2 to SP500 TR HAM3 to SP500 TR Alpha 0.0058 0.0091 0.0062 Beta 0.3901 0.3384 0.5523 @@ -7865,9 +8073,11 @@ Information Ratio 0.3604 0.5060 0.4701 Treynor Ratio 0.2428 0.3883 0.1956 > -> result = table.CAPM(managers[,1:3,drop=FALSE], managers[,8,drop=FALSE], Rf = managers[,10,drop=FALSE]) -> textplot(result, rmar = 0.8, cmar = 1.5, max.cex=.9, halign = "center", valign = "top", row.valign="center", wrap.rownames=15, wrap.colnames=10, mar = c(0,0,3,0)+0.1) -> title(main="CAPM-Related Statistics") +> result = table.SFM(managers[,1:3], managers[,8], Rf = managers[,10]) +> textplot(result, rmar = 0.8, cmar = 1.5, max.cex=.9, ++ halign = "center", valign = "top", row.valign="center", ++ wrap.rownames=15, wrap.colnames=10, mar = c(0,0,3,0)+0.1) +> title(main="Single Factor Model Related Statistics") > > > @@ -7906,36 +8116,46 @@ > # prettify with format.df in hmisc package > require("Hmisc") Loading required package: Hmisc +Loading required package: cluster +Loading required package: grid +Loading required package: lattice Loading required package: survival Loading required package: splines +Loading required package: Formula Hmisc library by Frank E Harrell Jr Type library(help='Hmisc'), ?Overview, or ?Hmisc.Overview') to see overall documentation. -NOTE:Hmisc no longer redefines [.factor to drop unused levels when -subsetting. To get the old behavior of Hmisc type dropUnusedLevels(). - Attaching package: ?Hmisc? -The following object(s) are masked from ?package:survival?: +The following objects are masked from ?package:survival?: - untangle.specials + survfitKM, untangle.specials -The following object(s) are masked from ?package:base?: +The following objects are masked from ?package:base?: format.pval, round.POSIXt, trunc.POSIXt, units > result = t(table.CalendarReturns(managers[,c(1,8)])) -> textplot(format.df(result, na.blank=TRUE, numeric.dollar=FALSE, cdec=rep(1,dim(result)[2])), rmar = 0.8, cmar = 1, max.cex=.9, halign = "center", valign = "top", row.valign="center", wrap.rownames=20, wrap.colnames=10, col.rownames=c( rep("darkgray",12), "black", "blue"), mar = c(0,0,3,0)+0.1) +> +> textplot(format.df(result, na.blank=TRUE, numeric.dollar=FALSE, ++ cdec=rep(1,dim(result)[2])), rmar = 0.8, cmar = 1, ++ max.cex=.9, halign = "center", valign = "top", ++ row.valign="center", wrap.rownames=20, wrap.colnames=10, ++ col.rownames=c( rep("darkgray",12), "black", "blue"), ++ mar = c(0,0,3,0)+0.1) +> > title(main="Calendar Returns") > > > > cleanEx() -detaching ?package:Hmisc?, ?package:survival?, ?package:splines? +detaching ?package:Hmisc?, ?package:Formula?, ?package:survival?, + ?package:splines?, ?package:lattice?, ?package:grid?, + ?package:cluster? > nameEx("table.CaptureRatios") > ### * table.CaptureRatios @@ -7977,7 +8197,10 @@ > > result = t(table.UpDownRatios(managers[,1:6], managers[,7,drop=FALSE])) > colnames(result)=colnames(managers[,1:6]) -> textplot(result, rmar = 0.8, cmar = 1.5, max.cex=.9, halign = "center", valign = "top", row.valign="center", wrap.rownames=15, wrap.colnames=10, mar = c(0,0,3,0)+0.1) +> textplot(result, rmar = 0.8, cmar = 1.5, max.cex=.9, [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3334 From noreply at r-forge.r-project.org Sun Feb 23 21:38:06 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 23 Feb 2014 21:38:06 +0100 (CET) Subject: [Returnanalytics-commits] r3335 - in pkg/PortfolioAnalytics: . R man Message-ID: <20140223203806.152071869B1@r-forge.r-project.org> Author: rossbennett34 Date: 2014-02-23 21:38:05 +0100 (Sun, 23 Feb 2014) New Revision: 3335 Removed: pkg/PortfolioAnalytics/man/portfolios.combine.Rd Modified: pkg/PortfolioAnalytics/R/generics.R pkg/PortfolioAnalytics/README pkg/PortfolioAnalytics/man/chart.EfficientFrontierOverlay.Rd Log: minor documentation edits Modified: pkg/PortfolioAnalytics/R/generics.R =================================================================== --- pkg/PortfolioAnalytics/R/generics.R 2014-02-23 16:47:32 UTC (rev 3334) +++ pkg/PortfolioAnalytics/R/generics.R 2014-02-23 20:38:05 UTC (rev 3335) @@ -93,7 +93,7 @@ #' print method for objects of class \code{summary.optimize.portfolio.rebalancing} #' #' @param x an object of class \code{summary.optimize.portfolio.rebalancing}. -#' @param ... any other passthru parameters +#' @param \dots any other passthru parameters #' @param digits number of digits used for printing #' @seealso \code{\link{summary.optimize.portfolio.rebalancing}} #' @author Ross Bennett Modified: pkg/PortfolioAnalytics/README =================================================================== --- pkg/PortfolioAnalytics/README 2014-02-23 16:47:32 UTC (rev 3334) +++ pkg/PortfolioAnalytics/README 2014-02-23 20:38:05 UTC (rev 3335) @@ -5,4 +5,10 @@ All documentation is being done in roxygen as an experiment. We will not be checking in compiled .Rd help file source all the time, mostly just before CRAN releases, so do -R CMD roxygen -d PortfolioAnalytics from one directory up. \ No newline at end of file +R CMD roxygen -d PortfolioAnalytics from one directory up. + +Some the Rd files generated by Roxygen add a new line where there should not be one and will result in an R CMD Check warning. These files were manually edited, but will be overwritten the next time roxygen is run. + +Running the following command from the /PortfolioAnalytics directory is a temporary fix. + +svn revert man/chart.Weights.Rd man/chart.RiskReward.Rd man/plot.Rd man/print.optimize.portfolio.Rd man/chart.EfficientFrontier.Rd man/chart.RiskBudget.Rd man/print.summary.optimize.portfolio.rebalancing.Rd \ No newline at end of file Modified: pkg/PortfolioAnalytics/man/chart.EfficientFrontierOverlay.Rd =================================================================== --- pkg/PortfolioAnalytics/man/chart.EfficientFrontierOverlay.Rd 2014-02-23 16:47:32 UTC (rev 3334) +++ pkg/PortfolioAnalytics/man/chart.EfficientFrontierOverlay.Rd 2014-02-23 20:38:05 UTC (rev 3335) @@ -16,7 +16,8 @@ \item{R}{an xts object of asset returns} \item{portfolio_list}{list of portfolio objects created - by \code{\link{portfolio.spec}}} + by \code{\link{portfolio.spec}} and combined with + \code{\link{combine.portfolios}}} \item{type}{type of efficient frontier, see \code{\link{create.EfficientFrontier}}} Deleted: pkg/PortfolioAnalytics/man/portfolios.combine.Rd =================================================================== --- pkg/PortfolioAnalytics/man/portfolios.combine.Rd 2014-02-23 16:47:32 UTC (rev 3334) +++ pkg/PortfolioAnalytics/man/portfolios.combine.Rd 2014-02-23 20:38:05 UTC (rev 3335) @@ -1,20 +0,0 @@ -\name{portfolios.combine} -\alias{portfolios.combine} -\title{Combine objects created by portfolio} -\usage{ - portfolios.combine(x) -} -\arguments{ - \item{x}{a list of objects created by - \code{\link{portfolio.spec}}} -} -\value{ - a \code{portfolio.list} object -} -\description{ - This function takes a list of objects created by - \code{\link{portfolio.spec}} and sets the class name - attribute to 'portfolio.list' for use in generic - functions -} - From noreply at r-forge.r-project.org Tue Feb 25 20:47:36 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 25 Feb 2014 20:47:36 +0100 (CET) Subject: [Returnanalytics-commits] r3336 - in pkg/PerformanceAnalytics/sandbox: . PAenhance PAenhance/R PAenhance/inst PAenhance/man Message-ID: <20140225194736.AB6B7186828@r-forge.r-project.org> Author: kecoli Date: 2014-02-25 20:47:36 +0100 (Tue, 25 Feb 2014) New Revision: 3336 Added: pkg/PerformanceAnalytics/sandbox/PAenhance/ pkg/PerformanceAnalytics/sandbox/PAenhance/R/ pkg/PerformanceAnalytics/sandbox/PAenhance/R/chart.Boxplot.R pkg/PerformanceAnalytics/sandbox/PAenhance/R/chart.QQplot.R pkg/PerformanceAnalytics/sandbox/PAenhance/R/lpm.Rd pkg/PerformanceAnalytics/sandbox/PAenhance/inst/ pkg/PerformanceAnalytics/sandbox/PAenhance/inst/PA-KirkLi.Rnw pkg/PerformanceAnalytics/sandbox/PAenhance/inst/PA-KirkLi.pdf pkg/PerformanceAnalytics/sandbox/PAenhance/man/ pkg/PerformanceAnalytics/sandbox/PAenhance/man/chart.Boxplot.Rd pkg/PerformanceAnalytics/sandbox/PAenhance/man/chart.QQPlot.Rd pkg/PerformanceAnalytics/sandbox/PAenhance/man/lpm.R Log: commit to sandbox/PAenhance, major changes on chart.Boxplot.R and chart.QQplot.R per comments made by Douglass Martin. Plan to merge to trunk version soon. For details see sandbox/PAenhance/inst/PA-KirkLi.pdf Added: pkg/PerformanceAnalytics/sandbox/PAenhance/R/chart.Boxplot.R =================================================================== --- pkg/PerformanceAnalytics/sandbox/PAenhance/R/chart.Boxplot.R (rev 0) +++ pkg/PerformanceAnalytics/sandbox/PAenhance/R/chart.Boxplot.R 2014-02-25 19:47:36 UTC (rev 3336) @@ -0,0 +1,423 @@ +#' box whiskers plot wrapper +#' +#' A wrapper to create box and whiskers plot with some defaults useful for +#' comparing distributions. +#' +#' We have also provided controls for all the symbols and lines in the chart. +#' One default, set by \code{as.Tufte=TRUE}, will strip chartjunk and draw a +#' Boxplot per recommendations by Edward Tufte. Another default, set by \code{as.Notch=TRUE}, will draw a notch in each side of the boxes. It can also be useful when comparing several series to sort them in the order of ascending or descending return or risk measurement by use of \code{sort.by} and \code{sort.ascending=TRUE}. In addition, one can compare this with another user specified order, called base order, e.g., to see the relative change of the orders of the series between two measurements of interest. +#' +#' +#' @param R an xts, vector, matrix, data frame, timeSeries or zoo object of +#' asset returns +#' @param horizontal TRUE/FALSE plot horizontal (TRUE) or vertical (FALSE) +#' @param names logical. if TRUE, show the names of each series +#' @param as.Tufte logical. default FALSE. if TRUE use method derived for Tufte +#' for limiting chartjunk +#' @param as.Notch logical. default FALSE. if TRUE a notch is drawn in each side of the boxes. +#' See \code{\link[graphics]{boxplot}} +#' @param sort.by one of the return or risk measure c("NULL", "mean", "median", "variance", "sharp ratio", "mean absolute deviation", "std dev", "sterling ratio", "calmar ratio", "burke ratio", "pain index", "ulcer index","martin ratio", "downside risk", "omega ratio", "sortino ratio", "upside risk","upside potential ratio", "omega sharpe ratio"). default is "NULL". +#' @param sort.base one of the return or risk measure as listed in \code{sort.by}, +#' add the base order number next to the labels sorted by \code{sort.by} +#' @param sort.ascending logical. If TRUE sort the distributions by ascending +#' \code{sort.by} and \code{sort.base} +#' @param colorset color palette to use, set by default to rational choices +#' @param symbol.color draws the symbols described in +#' \code{mean.symbol},\code{median.symbol},\code{outlier.symbol} in the color +#' specified +#' @param mean.symbol symbol to use for the mean of the distribution +#' @param median.symbol symbol to use for the median of the distribution +#' @param outlier.symbol symbol to use for the outliers of the distribution +#' @param show.data numerical vector of column numbers to display on top of +#' boxplot, default NULL +#' @param add.mean logical. if TRUE, show a line for the mean of all +#' distributions plotted +#' @param xlab set the x-axis label, same as in \code{\link{plot}} +#' @param main set the chart title, same as in \code{\link{plot}} +#' @param element.color specify the color of chart elements. Default is +#' "darkgray" +#' @param \dots any other passthru parameters +#' @return box plot of returns +#' @author Peter Carl +#' @author Ke Li \email{kirkli@@stat.washington.edu} +#' @seealso \code{\link[graphics]{boxplot}} +#' @references Tufte, Edward R. \emph{The Visual Display of Quantitative +#' Information}. Graphics Press. 1983. p. 124-129 +#' @keywords ts multivariate distribution models hplot +#' @examples +#' +#' data(edhec) +#' chart.Boxplot(edhec) +#' chart.Boxplot(edhec,as.Tufte=TRUE) +#' chart.Boxplot(R=edhec,sort.by="upside risk", +#' horizontal=TRUE, sort.base="std dev", +#' sort.ascending=TRUE) +#' @export +chart.Boxplot <- + function (R, horizontal = TRUE, names = TRUE, as.Tufte = FALSE, as.Notch=FALSE, sort.by = NULL, sort.base=NULL, sort.ascending = FALSE, colorset = "black", symbol.color = "red", mean.symbol = 1, median.symbol = "|", outlier.symbol = 1, show.data = NULL, add.mean = TRUE, xlab="Return", main = "Return Distribution Comparison", element.color = "darkgray", ...) +{ # @ author Peter Carl, updated by Kirk Li. + # DESCRIPTION: + # A wrapper to create box and whiskers plot, but with some sensible defaults + # useful for comparing distributions. + + # mar: a numerical vector of the form c(bottom, left, top, right) which + # gives the number of lines of margin to be specified on the four sides + # of the plot. The default is c(5, 4, 4, 2) + 0.1 + + sort.by <- tolower(sort.by) + + sort.by = sort.by[1] + + pool <- c("NA","mean", "median", "variance", "sharp ratio", "mean absolute deviation", "std dev", "sterling ratio", "calmar ratio", "burke ratio", "pain index", "ulcer index","martin ratio", "downside risk", "omega ratio", "sortino ratio", "upside risk","upside potential ratio", "omega sharpe ratio") + + sort.by <- match.arg(sort.by, pool, several.ok = FALSE) + + R = checkData(R, method="data.frame") + R.xts = checkData(R,method="xts") + columns = ncol(R) + rows = nrow(R) + columnnames = colnames(R) + + column.order = NULL + + sort.by <- tolower(sort.by) + + sort.by = sort.by[1] + + op <- par(no.readonly=TRUE) + + if(names){ + par(mar=c(5,12,4,2) + 0.2) + } + + if(length(colorset) < columns) + colorset = rep(colorset, length.out = columns) + + if(length(symbol.color) < columns) + symbol.color = rep(symbol.color, length.out = columns) + + if(length(mean.symbol) < columns) + mean.symbol = rep(mean.symbol, length.out = columns) + + means = sapply(R, mean, na.rm = TRUE) + + + asc.desc <- ifelse(sort.ascending,"ascending","descending") + + switch(sort.by, + mean = { + column.order = order(means, decreasing=!sort.ascending) + sort.by = paste("Mean", sep="") + }, + median = { + medians = sapply(R, median, na.rm = TRUE) + column.order = order(medians, decreasing=!sort.ascending) + sort.by = paste("Median", sep="") + }, + variance = { + variances = sapply(R, var, na.rm = TRUE) + column.order = order(variances, decreasing=!sort.ascending) + sort.by = paste("Variance", sep="") + }, + "sharp ratio" = { + sharpratio = sapply(R,function(x)mean(x,na.rm = TRUE)/sd(x,na.rm = TRUE)) + column.order = order(sharpratio, decreasing=!sort.ascending) + sort.by = paste("Sharp Ratio",sep="") + }, + "mean absolute deviation" = { + MeanAbsoluteDeviation = sapply(R,MeanAbsoluteDeviation) + column.order = order(MeanAbsoluteDeviation, decreasing=!sort.ascending) + sort.by = paste("Mean Absolute Dev",sep="") + }, + "std dev" = { + StdDev.annualized = sapply(R.xts,function(x)StdDev.annualized(x)) + column.order = order(StdDev.annualized, decreasing=!sort.ascending) + sort.by = paste("Std Dev",sep="") + }, + "sterling ratio" = { + SterlingRatio = sapply(R.xts,SterlingRatio) + column.order = order(SterlingRatio, decreasing=!sort.ascending) + sort.by = paste("Sterling Ratio",sep="") + }, + "calmar ratio" = { + CalmarRatio = sapply(R.xts,CalmarRatio) + column.order = order(CalmarRatio, decreasing=!sort.ascending) + sort.by = paste("Calmar Ratio",sep="") + }, + "burke ratio" = { + BurkeRatio = sapply(R.xts,BurkeRatio) + column.order = order(BurkeRatio, decreasing=!sort.ascending) + sort.by = paste("Burke Ratio",sep="") + }, + "pain index" = { + PainIndex = sapply(R,PainIndex) + column.order = order(PainIndex, decreasing=!sort.ascending) + sort.by = paste("Pain Index",sep="") + }, + "ulcer index" = { + UlcerIndex = sapply(R,UlcerIndex) + column.order = order(UlcerIndex, decreasing=!sort.ascending) + sort.by = paste("Ulcer Index",sep="") + }, + "martin ratio" = { + MartinRatio = sapply(R.xts,MartinRatio) + column.order = order(MartinRatio, decreasing=!sort.ascending) + sort.by = paste("Martin Ratio",sep="") + }, + "downside risk" = { + DownsideDeviation = sapply(R,DownsideDeviation) + column.order = order(DownsideDeviation, decreasing=!sort.ascending) + sort.by = paste("Downside Risk",sep="") + }, + "omega ratio" = { + Omega = sapply(R,Omega) + column.order = order(Omega, decreasing=!sort.ascending) + sort.by = paste("Omega Ratio",sep="") + }, + "sortino ratio" = { + SortinoRatio = sapply(R,SortinoRatio) + column.order = order(SortinoRatio, decreasing=!sort.ascending) + sort.by = paste("Sortino Ratio",sep="") + }, + "upside risk" = { + UpsideRisk = sapply(R,UpsideRisk) + column.order = order(UpsideRisk, decreasing=!sort.ascending) + sort.by = paste("Upside Risk",sep="") + }, + "upside potential ratio" = { + UpsidePotentialRatio = sapply(R,UpsidePotentialRatio) + column.order = order(UpsidePotentialRatio, decreasing=!sort.ascending) + sort.by = paste("Upside Potential Ratio",sep="") + }, + "omega sharpe ratio" = { + OmegaSharpeRatio = sapply(R,OmegaSharpeRatio) + column.order = order(OmegaSharpeRatio, decreasing=!sort.ascending) + sort.by = paste("Omega Sharpe Ratio",sep="") + }, + { + column.order = 1:columns + sort.by = paste("Unsorted", sep="") + } + ) # end switch + + ylab=paste("Sorted by:",asc.desc,sort.by) + + + # base order + if(!is.null(sort.base)){ + colum.order.base = NULL + + sort.base <- tolower(sort.base) + + sort.base <- match.arg(sort.base, pool, several.ok = FALSE) + + switch(sort.base, + mean = { + means = sapply(R, mean, na.rm = TRUE) + column.order.base = order(means, decreasing=!sort.ascending) + sort.base = paste("Mean", sep="") + }, + median = { + medians = sapply(R, median, na.rm = TRUE) + column.order.base = order(medians, decreasing=!sort.ascending) + sort.base = paste("Median", sep="") + }, + variance = { + variances = sapply(R, var, na.rm = TRUE) + column.order.base = order(variances, decreasing=!sort.ascending) + sort.base = paste("Variance", sep="") + }, + "sharp ratio" = { + sharpratio = sapply(R,function(x)mean(x,na.rm = TRUE)/sd(x,na.rm = TRUE)) + column.order.base = order(sharpratio, decreasing=!sort.ascending) + sort.base = paste("Sharp Ratio",sep="") + }, + "mean absolute deviation" = { + MeanAbsoluteDeviation = sapply(R,MeanAbsoluteDeviation) + column.order.base = order(MeanAbsoluteDeviation, decreasing=!sort.ascending) + sort.base = paste("Mean Absolute Dev",sep="") + }, + "std dev" = { + StdDev.annualized = sapply(R.xts,StdDev.annualized) + column.order.base = order(StdDev.annualized, decreasing=!sort.ascending) + sort.base = paste("Std Dev",sep="") + }, + "sterling ratio" = { + SterlingRatio = sapply(R.xts,SterlingRatio) + column.order.base = order(SterlingRatio, decreasing=!sort.ascending) + sort.base = paste("Sterling Ratio",sep="") + }, + "calmar ratio" = { + CalmarRatio = sapply(R.xts,function(x)mean(x,na.rm = TRUE)/sd(x,na.rm = TRUE)) + column.order.base = order(CalmarRatio, decreasing=!sort.ascending) + sort.base = paste("Calmar Ratio",sep="") + }, + "burke ratio" = { + BurkeRatio = sapply(R.xts,BurkeRatio) + column.order.base = order(BurkeRatio, decreasing=!sort.ascending) + sort.base = paste("Burke Ratio",sep="") + }, + "ulcer index" = { + UlcerIndex = sapply(R,UlcerIndex) + column.order.base = order(UlcerIndex, decreasing=!sort.ascending) + sort.base = paste("Ulcer Index",sep="") + }, + "pain index" = { + PainRatio = sapply(R.xts,PainRatio) + column.order.base = order(PainRatio, decreasing=!sort.ascending) + sort.base = paste("Pain Index",sep="") + }, + "martin ratio" = { + MartinRatio = sapply(R.xts,MartinRatio) + column.order.base = order(MartinRatio, decreasing=!sort.ascending) + sort.base = paste("Martin Ratio",sep="") + }, + "downside risk" = { + DownsideDeviation = sapply(R,DownsideDeviation) + column.order.base = order(DownsideDeviation, decreasing=!sort.ascending) + sort.base = paste("Downside Risk",sep="") + }, + "omega ratio" = { + Omega = sapply(R,Omega) + column.order.base = order(Omega, decreasing=!sort.ascending) + sort.base = paste("Omega Ratio",sep="") + }, + "sortino ratio" = { + SortinoRatio = sapply(R,SortinoRatio) + column.order.base = order(SortinoRatio, decreasing=!sort.ascending) + sort.base = paste("Sortino Ratio",sep="") + }, + "upside risk" = { + UpsideRisk = sapply(R,UpsideRisk) + column.order.base = order(UpsideRisk, decreasing=!sort.ascending) + sort.base = paste("Upside Risk",sep="") + }, + "upside potential ratio" = { + UpsidePotentialRatio = sapply(R,UpsidePotentialRatio) + column.order.base = order(UpsidePotentialRatio, decreasing=!sort.ascending) + sort.base = paste("Upside Potential Ratio",sep="") + }, + "omega sharpe ratio" = { + OmegaSharpeRatio = sapply(R,OmegaSharpeRatio) + column.order.base = order(OmegaSharpeRatio, decreasing=!sort.ascending) + sort.base = paste("Omega Sharpe Ratio",sep="") + }, + { + column.order.base = 1:columns + sort.base = paste("Unsorted", sep="") + } + ) # end switch + + ylab.base=paste(asc.desc,sort.base) + } + + if(horizontal) { + par(mar=c(5,8,4,2)+1) + column.order.box <- rev(column.order) + if(!is.null(sort.base)) + column.order.base.box <- rev(column.order.base) + } else { + par(mar=c(8,4,4,2)+1) + column.order.box <- column.order + if(!is.null(sort.base)) + column.order.base.box <- column.order.base + + } + + + if(as.Tufte){ + boxplot(R[,column.order.box], horizontal = horizontal, names = names, main = main, xlab = ifelse(horizontal,xlab,""), ylab = ifelse(horizontal,"",xlab), pars = list(boxcol = "white", medlty = "blank", medpch = median.symbol, medlwd = 2, medcex = .8, medcol = colorset[column.order.box], whisklty = c(1,1), whiskcol = colorset[column.order.box], staplelty = "blank", outpch = outlier.symbol, outcex = .5, outcol = colorset[column.order.box] ), axes = FALSE, cex.lab=0.7,...) + mtext(side=3,text=ylab,cex=0.7) + if(!is.null(sort.base)) + mtext(side=3, + text=paste("Base order: ",ylab.base,sep=" "),line=1,cex=0.7) + } else if(as.Notch){ + + boxplot(R[,column.order.box], horizontal = horizontal, names = names, main = main, xlab = ifelse(horizontal,xlab,""), ylab = ifelse(horizontal,"",xlab), pars = list(boxcol = colorset[column.order.box], medlwd = 1, medcol = colorset[column.order.box], whisklty = c(1,1), whiskcol = colorset[column.order.box], staplelty = 1, staplecol = colorset[column.order.box], staplecex = .5, outpch = outlier.symbol, outcex = .5, outcol = colorset[column.order.box] ), axes = FALSE, boxwex=.6, cex.lab=0.7, notch=TRUE,...) + mtext(side=3,text=ylab,cex=0.7) + + if(!is.null(sort.base)) + mtext(side=3, + text=paste("Base order: ",ylab.base,sep=" "),line=1,cex=0.7) + } else{ + + boxplot(R[,column.order.box], horizontal = horizontal, names = names, main = main, xlab = ifelse(horizontal,xlab,""), ylab = ifelse(horizontal,"",xlab), pars = list(boxcol = colorset[column.order.box], medlwd = 1, medcol = colorset[column.order.box], whisklty = c(1,1), whiskcol = colorset[column.order.box], staplelty = 1, staplecol = colorset[column.order.box], staplecex = .5, outpch = outlier.symbol, outcex = .5, outcol = colorset[column.order.box] ), axes = FALSE, boxwex=.6, cex.lab=0.7,...) + mtext(side=3,text=ylab,cex=0.7) + if(!is.null(sort.base)) + mtext(side=3, + text=paste("Base order: ", ylab.base,sep=" "),line=1,cex=0.7) + } # end else + + if(!is.null(show.data)) { + highlight.color=1:24 + for (item in show.data) { + points(as.vector(R[item,column.order]), 1:columns, col=highlight.color[item]) #, pch = mean.symbol[column.order], col=symbol.color[column.order]) + } + } + + if(add.mean){ + if(horizontal) + points(means[column.order], columns:1, pch = mean.symbol[column.order], col=symbol.color[column.order],cex=0.5) else + points(1:columns, means[column.order], pch = mean.symbol[column.order], col=symbol.color[column.order],cex=0.5) + } + + if(names){ + if(!is.null(sort.base)){ + if(horizontal){ + labels = paste(columnnames[column.order]," ",sep="") + labels.sec =paste("(",(match(column.order,column.order.base)),")",sep="") + labels=rev(labels) + } else{ + labels = paste(columnnames[column.order]," ",sep="") + labels.sec = paste("(",match(column.order,column.order.base),")",sep="") + } + } else labels = columnnames[column.order] + + if(!horizontal){ +# axis(1,labels=FALSE) + text(1:length(labels), par("usr")[1] - 0.2, srt = 45, adj = 1, + labels = labels, xpd = TRUE, cex=0.7) + if(!is.null(sort.base)) + text(1:length(labels), par("usr")[1] - 0.2, srt = 0, adj = 1, + labels = labels.sec, xpd = TRUE, cex=0.5) + ## Plot x axis label at line 6 (of 7) + }else{ +# axis(2, cex.axis = 0.9, col = element.color, labels = labels, at = 1:columns, las = 2) + text(par("usr")[3] - 0.24, 1:length(labels), srt = 0, adj = 1, + labels = labels, xpd = TRUE, cex=0.7) + if(!is.null(sort.base)) + text(par("usr")[3] - 0.24, 1:length(labels), srt = 0, adj = 0, + labels = labels.sec, xpd = TRUE, cex=0.5) + } + } else{ + labels = "" + axis(2, cex.axis = 0.8, col = element.color, labels = labels, at = 1:columns, las = 1, tick = FALSE) + } + +# if(names) +# title(sub=ylab) +# else +# title(sub=ylab) + box(col=element.color) + + if(horizontal) { + abline(v=0, lty="solid",col=element.color) + } else { + abline(h=0, lty="solid",col=element.color) + } + + + par(op) +} + +############################################################################### +# R (http://r-project.org/) Econometrics for Performance and Risk Analysis +# +# Copyright (c) 2004-2012 Peter Carl and Brian G. Peterson +# +# This R package is distributed under the terms of the GNU Public License (GPL) +# for full details see the file COPYING +# +# $Id: chart.Boxplot.R 2621 2013-07-22 19:36:44Z peter_carl $ +# +############################################################################### Added: pkg/PerformanceAnalytics/sandbox/PAenhance/R/chart.QQplot.R =================================================================== --- pkg/PerformanceAnalytics/sandbox/PAenhance/R/chart.QQplot.R (rev 0) +++ pkg/PerformanceAnalytics/sandbox/PAenhance/R/chart.QQplot.R 2014-02-25 19:47:36 UTC (rev 3336) @@ -0,0 +1,311 @@ +#' Plot a QQ chart +#' +#' Plot the return data against any theoretical distribution. +#' +#' A Quantile-Quantile (QQ) plot is a scatter plot designed to compare the data +#' to the theoretical distributions to visually determine if the observations +#' are likely to have come from a known population. The empirical quantiles are +#' plotted to the y-axis, and the x-axis contains the values of the theorical +#' model. A 45-degree reference line is also plotted. If the empirical data +#' come from the population with the choosen distribution, the points should +#' fall approximately along this reference line. The larger the departure from +#' the reference line, the greater the evidence that the data set have come +#' from a population with a different distribution. +#' +#' @param R an xts, vector, matrix, data frame, timeSeries or zoo object of +#' asset returns +#' @param distribution root name of comparison distribution - e.g., 'norm' for +#' the normal distribution; 't' for the t-distribution. See examples for other +#' ideas. +#' @param xlab set the x-axis label, as in \code{\link{plot}} +#' @param ylab set the y-axis label, as in \code{\link{plot}} +#' @param xaxis if true, draws the x axis +#' @param yaxis if true, draws the y axis +#' @param ylim set the y-axis limits, same as in \code{\link{plot}} +#' @param main set the chart title, same as in \code{plot} +#' @param las set the direction of axis labels, same as in \code{plot} +#' @param envelope confidence level for point-wise confidence envelope, or +#' FALSE for no envelope. +#' @param labels vector of point labels for interactive point identification, +#' or FALSE for no labels. +#' @param col color for points and lines; the default is the \emph{second} +#' entry in the current color palette (see 'palette' and 'par'). +#' @param lwd set the line width, as in \code{\link{plot}} +#' @param pch symbols to use, see also \code{\link{plot}} +#' @param cex symbols to use, see also \code{\link{plot}} +#' @param line 'quartiles' to pass a line through the quartile-pairs, or +#' 'robust' for a robust-regression line; the latter uses the 'rlm' function +#' in the 'MASS' package. Specifying 'line = "none"' suppresses the line. +#' @param element.color provides the color for drawing chart elements, such as +#' the box lines, axis lines, etc. Default is "darkgray" +#' @param cex.legend The magnification to be used for sizing the legend +#' relative to the current setting of 'cex' +#' @param cex.axis The magnification to be used for axis annotation relative to +#' the current setting of 'cex' +#' @param cex.lab The magnification to be used for x- and y-axis labels +#' relative to the current setting of 'cex' +#' @param cex.main The magnification to be used for the main title relative to +#' the current setting of 'cex'. +#' @param \dots any other passthru parameters to the distribution function +#' +#' @author John Fox, ported by Peter Carl +#' @author For QQplot with mixture normal distribution, Ke Li \email{kirkli@@stat.washington.edu} +#' @seealso +#' \code{\link[stats]{qqplot}} \cr +#' \code{\link[car]{qq.plot}} \cr +#' \code{\link{plot}} \cr +#' CRAN package \code{\link[nor1mix]{norMixFit}} for mixture normal distribution +#' @references main code forked/borrowed/ported from the excellent: \cr Fox, +#' John (2007) \emph{car: Companion to Applied Regression} \cr +#' \url{http://www.r-project.org}, +#' \url{http://socserv.socsci.mcmaster.ca/jfox/} +#' @keywords ts multivariate distribution models hplot +#' @examples +#,library(MASS) +#,data(managers) + +#,x = checkData(managers[,2, drop = FALSE], na.rm = TRUE, method = "vector") + +#layout(rbind(c(1,2),c(3,4))) + +# Panel 1, Normal distribution +#,chart.QQPlot(x, main = "Normal Distribution", distribution = 'norm', envelope=0.95) +# Panel 2, Log-Normal distribution +#,fit = fitdistr(1+x, 'lognormal') +#,chart.QQPlot(1+x, main = "Log-Normal Distribution", envelope=0.95, distribution='lnorm') +#other options could include +#, meanlog = fit$estimate[[1]], sdlog = fit$estimate[[2]]) + +#,\dontrun{ +#, # Panel 3, Skew-T distribution +#, library(sn) +#, fit = st.mle(y=x) +#, chart.QQPlot(x, main = "Skew T Distribution", envelope=0.95, +#, distribution = 'st', location = fit$dp[[1]], +#, scale = fit$dp[[2]], shape = fit$dp[[3]], df=fit$dp[[4]]) +#, +# Panel 4: Stable Parietian +#,library(fBasics) +#,fit.stable = stableFit(x,doplot=FALSE) +#,chart.QQPlot(x, main = "Stable Paretian Distribution", envelope=0.95, +#, distribution = 'stable', alpha = fit(stable.fit)$estimate[[1]], +#, beta = fit(stable.fit)$estimate[[2]], gamma = fit(stable.fit)$estimate[[3]], +#, delta = fit(stable.fit)$estimate[[4]], pm = 0) +#, +#,Panel 5: Mixture Normal distribution +#,chart.QQPlot(x, main = "Normal Mixture Distribution", +#, line=c("quartiles"), para=list(m=2), distribution = 'mixnormal', +#, envelope=0.95) +#,} +#' +#' #end examples +#' +#' @export + + + +chart.QQPlot <- + function(R, distribution="norm", ylab=NULL, + xlab=paste(distribution, "Quantiles"), main=NULL, las=par("las"), + envelope=FALSE, labels=FALSE, col=c(1,4), lwd=2, pch=1, cex=1, + line=c("quartiles", "robust", "none"), element.color = "darkgray", + cex.axis = 0.8, cex.legend = 0.8, cex.lab = 1, cex.main = 1, xaxis=TRUE, yaxis=TRUE, ylim=NULL, ...) + { # @author Peter Carl + + # DESCRIPTION: + # A wrapper to create a chart of relative returns through time + + # Inputs: + # R: a matrix, data frame, or timeSeries of returns + + # Outputs: + # A Normal Q-Q Plot + + # FUNCTION: + + x = checkData(R, method = "vector", na.rm = TRUE) + # n = length(x) + + if(is.null(main)){ + if(!is.null(colnames(R)[1])) + main=colnames(R)[1] + else + main = "QQ Plot" + } + if(is.null(ylab)) ylab = "Empirical Quantiles" + # the core of this function is taken from John Fox's qq.plot, which is part of the car package + result <- NULL + line <- match.arg(line) + good <- !is.na(x) + ord <- order(x[good]) + ord.x <- x[good][ord] + n <- length(ord.x) + P <- ppoints(n) + + if(distribution=="mixnormal") + { + qmixnormal <- function(q, ...){ + # norMix distribution + para=list(...)$para + + if(!is.list(para))stop(" 'para' must be a 'list' object") + + if(is.null(para$m)|is.na(para$m)) + stop("The number of component must be specified in 'para$m'") + + require(nor1mix) + out = norMixEM(x, para$m, trace=0) + + if (length(q)!=2){ + # only print once + print("fitted model:") + print(out[1:para$m,],digits=3) + } + if(is.null(para$mu) | is.null(para$sig2)) + # using fitted distribution + { + if (length(q)!=2) + print("using fitted model as theoretical distribution") + obj <- out + } else{ + # using specified distribution + if(length(para$mu)!=para$m | length(para$sig2)!=para$m) + stop("the number of components mismatch with parameter inputs") + + obj <- norMix(mu = para$mu, sig2 = para$sig2, w = para$w) + } + qnorMix(q,obj) + } + + + dmixnormal<- function(p, ...){ + # norMix distribution + para=list(...)$para + if(!is.list(para))stop(" 'para' must be a 'list' object") + if(is.null(para$m)|is.na(para$m)) + stop("The number of component must be specified in 'para$m'") + library(nor1mix) + out = norMixEM(x, para$m, trace=0) + + if(is.null(para$mu) | is.null(para$sig2)) + # using fitted distribution + { + obj <- out + } else{ + # using specified distribution + if(length(para$mu) != para$m | length(para$sig2) != para$m) + stop("the number of components mismatch with parameter inputs") + + obj <- norMix(mu = para$mu, sig2 = para$sig2, w = para$w) + } + dnorMix(p,obj) + } + + } + + + q.function <- eval(parse(text=paste("q",distribution, sep=""))) + d.function <- eval(parse(text=paste("d",distribution, sep=""))) + + z <- q.function(P,...) + + plot(z, ord.x, xlab=xlab, ylab=ylab, main=main, las=las, col=col[1], pch=pch, + cex=cex, cex.main = cex.main, cex.lab = cex.lab, axes=FALSE, ylim=ylim) + + if (line=="quartiles"){ + Q.x<-quantile(ord.x, c(.25,.75)) + Q.z<-q.function(c(.25,.75), ...) + b<-(Q.x[2]-Q.x[1])/(Q.z[2]-Q.z[1]) + a<-Q.x[1]-b*Q.z[1] + abline(a, b, col=col[2], lwd=lwd) + } + if (line=="robust"){ + stopifnot("package:MASS" %in% search() || require("MASS",quietly=TRUE)) + coef<-coefficients(rlm(ord.x~z)) + a<-coef[1] + b<-coef[2] + abline(a,b, col=col[2]) + } + if (line != 'none' & envelope != FALSE) { + zz<-qnorm(1-(1-envelope)/2) + SE<-(b/d.function(z,...))*sqrt(P*(1-P)/n) + fit.value<-a+b*z + upper<-fit.value+zz*SE + lower<-fit.value-zz*SE + lines(z, upper, lty=2, lwd=lwd/2, col=col[2]) + lines(z, lower, lty=2, lwd=lwd/2, col=col[2]) + } + if (labels[1]==TRUE & length(labels)==1) labels<-seq(along=z) + if (labels[1] != FALSE) { + selected<-identify(z, ord.x, labels[good][ord]) + result <- seq(along=x)[good][ord][selected] + } + if (is.null(result)) invisible(result) else sort(result) + + # if(distribution == "normal") { + # if(is.null(xlab)) xlab = "Normal Quantiles" + # if(is.null(ylab)) ylab = "Empirical Quantiles" + # if(is.null(main)) main = "Normal QQ-Plot" + # + # # Normal Quantile-Quantile Plot: + # qqnorm(x, xlab = xlab, ylab = ylab, main = main, pch = symbolset, axes = FALSE) + # # qqline(x, col = colorset[2], lwd = 2) + # q.theo = qnorm(c(0.25,0.75)) + # } + # if(distribution == "sst") { + # library("sn") + # if(is.null(xlab)) xlab = "Skew-T Quantiles" + # if(is.null(ylab)) ylab = "Empirical Quantiles" + # if(is.null(main)) main = "Skew-T QQ-Plot" + # + # # Skew Student-T Quantile-Quantile Plot: + # y = qst(c(1:n)/(n+1)) + # qqplot(y, x, xlab = xlab, ylab = ylab, axes=FALSE, main=main) + # q.theo = qst(c(0.25,0.75)) + # } + # if(distribution == "cauchy") { + # if(is.null(xlab)) xlab = "Cauchy Quantiles" + # if(is.null(ylab)) ylab = "Empirical Quantiles" + # if(is.null(main)) main = "Cauchy QQ-Plot" + # + # # Skew Student-T Quantile-Quantile Plot: + # y = qcauchy(c(1:n)/(n+1)) + # qqplot(y, x, xlab = xlab, ylab = ylab, axes=FALSE, main=main) + # q.theo = qcauchy(c(0.25,0.75)) + # } + # if(distribution == "lnorm") { + # if(is.null(xlab)) xlab = "Log Normal Quantiles" + # if(is.null(ylab)) ylab = "Empirical Quantiles" + # if(is.null(main)) main = "Log Normal QQ-Plot" + # + # # Skew Student-T Quantile-Quantile Plot: + # y = qlnorm(c(1:n)/(n+1)) + # qqplot(y, x, xlab = xlab, ylab = ylab, axes=FALSE, main=main) + # q.theo = qlnorm(c(0.25,0.75)) + # } + # + # q.data=quantile(x,c(0.25,0.75)) + # slope = diff(q.data)/diff(q.theo) + # int = q.data[1] - slope* q.theo[1] + # + # if(line) abline(int, slope, col = colorset[2], lwd = 2) + if(xaxis) + axis(1, cex.axis = cex.axis, col = element.color) + if(yaxis) + axis(2, cex.axis = cex.axis, col = element.color) + + box(col=element.color) + + } + +############################################################################### +# R (http://r-project.org/) Econometrics for Performance and Risk Analysis +# +# Copyright (c) 2004-2014 Peter Carl and Brian G. Peterson +# +# This R package is distributed under the terms of the GNU Public License (GPL) +# for full details see the file COPYING +# +# $Id: chart.QQPlot.R 3301 2014-01-18 15:26:12Z braverock $ +# +############################################################################### Added: pkg/PerformanceAnalytics/sandbox/PAenhance/R/lpm.Rd =================================================================== --- pkg/PerformanceAnalytics/sandbox/PAenhance/R/lpm.Rd (rev 0) +++ pkg/PerformanceAnalytics/sandbox/PAenhance/R/lpm.Rd 2014-02-25 19:47:36 UTC (rev 3336) @@ -0,0 +1,30 @@ +\name{lpm} +\alias{lpm} +\title{calculate the lower partial moment of a time series} +\usage{ +lpm(R, n, threshold, about_mean = FALSE) +} +\arguments{ + \item{R}{xts data} + + \item{n}{the n-th moment to return} + + \item{threshold}{threshold can be the mean or any point + as desired} + + \item{about_mean}{TRUE/FALSE calculate LPM about the mean + under the threshold or use the threshold to calculate the + LPM around (if FALSE)} +} +\description{ +Code to calculate the Lower Partion Moments around the mean +or a specified threshold from Huffman S,P & Moll C.R. 2011 +"The impact of Asymmetry on Expected Stock Returns: An +Investigation of Alternative Risk Measures" Algorithmic +Finance 1 (2011) 79-93 +} +\author{ +Kyle Balkissoon \email{kylebalkissoon at gmail.com} +\email{kyle at corporateknights.com} +} + Added: pkg/PerformanceAnalytics/sandbox/PAenhance/inst/PA-KirkLi.Rnw =================================================================== --- pkg/PerformanceAnalytics/sandbox/PAenhance/inst/PA-KirkLi.Rnw (rev 0) +++ pkg/PerformanceAnalytics/sandbox/PAenhance/inst/PA-KirkLi.Rnw 2014-02-25 19:47:36 UTC (rev 3336) @@ -0,0 +1,142 @@ +% +\documentclass[a4paper]{article} +\usepackage{Sweave} +\usepackage{listings} +\title{PerformanceAnalytics Changed by Kirk Li} +\author{kirkli at u.washington.edu} + +\begin{document} + +\maketitle + +\tableofcontents + +<>= +# global chunk options +library(knitr) +opts_chunk$set(cache=FALSE, tidy=FALSE, autodep=TRUE, + fig.width=6, fig.height=6) +options(width=60) +listing <- function(x, options) { + paste("\\begin{lstlisting}[basicstyle=\\ttfamily,breaklines=true]\n", + x, "\\end{lstlisting}\n", sep = "") +} +knit_hooks$set(source=listing, output=listing) + + +@ + +<>= +library(PAKK) +library(nor1mix) +@ + +\section{Changes on chart.Boxplot} +Remarks: +\begin{itemize} + \item Sorting boxplot by different risk measure + \begin{itemize} + \item Enable the ascending sorting and descending sorting + \item Enable one of 18 measures that adopted from table.Distributions, + table.DrawdownsRatio, + table.DownsideRiskRatio, [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3336 From noreply at r-forge.r-project.org Tue Feb 25 20:56:17 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 25 Feb 2014 20:56:17 +0100 (CET) Subject: [Returnanalytics-commits] r3337 - in pkg/PerformanceAnalytics/sandbox/PAenhance: R man Message-ID: <20140225195617.C9E1C1869A6@r-forge.r-project.org> Author: kecoli Date: 2014-02-25 20:56:17 +0100 (Tue, 25 Feb 2014) New Revision: 3337 Removed: pkg/PerformanceAnalytics/sandbox/PAenhance/R/lpm.Rd pkg/PerformanceAnalytics/sandbox/PAenhance/man/lpm.R Log: delete misplaced file in sandbox/PAenhance Deleted: pkg/PerformanceAnalytics/sandbox/PAenhance/R/lpm.Rd =================================================================== --- pkg/PerformanceAnalytics/sandbox/PAenhance/R/lpm.Rd 2014-02-25 19:47:36 UTC (rev 3336) +++ pkg/PerformanceAnalytics/sandbox/PAenhance/R/lpm.Rd 2014-02-25 19:56:17 UTC (rev 3337) @@ -1,30 +0,0 @@ -\name{lpm} -\alias{lpm} -\title{calculate the lower partial moment of a time series} -\usage{ -lpm(R, n, threshold, about_mean = FALSE) -} -\arguments{ - \item{R}{xts data} - - \item{n}{the n-th moment to return} - - \item{threshold}{threshold can be the mean or any point - as desired} - - \item{about_mean}{TRUE/FALSE calculate LPM about the mean - under the threshold or use the threshold to calculate the - LPM around (if FALSE)} -} -\description{ -Code to calculate the Lower Partion Moments around the mean -or a specified threshold from Huffman S,P & Moll C.R. 2011 -"The impact of Asymmetry on Expected Stock Returns: An -Investigation of Alternative Risk Measures" Algorithmic -Finance 1 (2011) 79-93 -} -\author{ -Kyle Balkissoon \email{kylebalkissoon at gmail.com} -\email{kyle at corporateknights.com} -} - Deleted: pkg/PerformanceAnalytics/sandbox/PAenhance/man/lpm.R =================================================================== --- pkg/PerformanceAnalytics/sandbox/PAenhance/man/lpm.R 2014-02-25 19:47:36 UTC (rev 3336) +++ pkg/PerformanceAnalytics/sandbox/PAenhance/man/lpm.R 2014-02-25 19:56:17 UTC (rev 3337) @@ -1,54 +0,0 @@ -#' calculate the lower partial moment of a time series -#' -#' Code to calculate the Lower Partion Moments around the mean or a specified threshold -#' from Huffman S,P & Moll C.R. 2011 "The impact of Asymmetry on Expected Stock Returns: An Investigation of Alternative Risk Measures" Algorithmic Finance 1 (2011) 79-93 -#' -#' @param R xts data -#' @param n the n-th moment to return -#' @param threshold threshold can be the mean or any point as desired -#' @param about_mean TRUE/FALSE calculate LPM about the mean under the threshold or use the threshold to calculate the LPM around (if FALSE) -#' -#' @author Kyle Balkissoon \email{kylebalkissoon@@gmail.com} \email{kyle@@corporateknights.com} -#' @export -lpm <- function(R,n,threshold,about_mean=FALSE){ - - if(about_mean==TRUE){ - #Calculate Number of obs less than threshold - nb = nrow(x[x Author: peter_carl Date: 2014-02-25 23:51:30 +0100 (Tue, 25 Feb 2014) New Revision: 3338 Modified: pkg/PerformanceAnalytics/R/chart.Events.R Log: - fixed example to pass check Modified: pkg/PerformanceAnalytics/R/chart.Events.R =================================================================== --- pkg/PerformanceAnalytics/R/chart.Events.R 2014-02-25 19:56:17 UTC (rev 3337) +++ pkg/PerformanceAnalytics/R/chart.Events.R 2014-02-25 22:51:30 UTC (rev 3338) @@ -35,9 +35,8 @@ #' @examples #' \dontrun{ #' data(managers) -#' R = PerformanceAnalytics:::Drawdowns(managers[,2,drop=FALSE]) #' n = table.Drawdowns(managers[,2,drop=FALSE]) -#' chart.Events(PerformanceAnalytics:::Drawdowns(managers[,2,drop=FALSE]), +#' chart.Events(Drawdowns(managers[,2,drop=FALSE]), #' dates = n$Trough, #' prior=max(na.omit(n$"To Trough")), #' post=max(na.omit(n$Recovery)), From noreply at r-forge.r-project.org Wed Feb 26 00:46:32 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 26 Feb 2014 00:46:32 +0100 (CET) Subject: [Returnanalytics-commits] r3339 - pkg/PerformanceAnalytics/R Message-ID: <20140225234632.5F1E7185EAD@r-forge.r-project.org> Author: peter_carl Date: 2014-02-26 00:46:31 +0100 (Wed, 26 Feb 2014) New Revision: 3339 Modified: pkg/PerformanceAnalytics/R/Return.calculate.R pkg/PerformanceAnalytics/R/chart.RollingPerformance.R pkg/PerformanceAnalytics/R/chart.TimeSeries.R pkg/PerformanceAnalytics/R/decomposeMVaR.R Log: - removed ':::' to internal functions and exported xts functions Modified: pkg/PerformanceAnalytics/R/Return.calculate.R =================================================================== --- pkg/PerformanceAnalytics/R/Return.calculate.R 2014-02-25 22:51:30 UTC (rev 3338) +++ pkg/PerformanceAnalytics/R/Return.calculate.R 2014-02-25 23:46:31 UTC (rev 3339) @@ -70,7 +70,7 @@ if(method=="simple" || method=='discrete'){ #Returns = pr/pr[-nrow(pr), ] - 1 - Returns = pr/xts:::lagts.xts(pr) - 1 + Returns = pr/lag(pr) - 1 xtsAttributes(Returns) <- list(ret_type="discrete") } if(method=="compound" || method=='log') { Modified: pkg/PerformanceAnalytics/R/chart.RollingPerformance.R =================================================================== --- pkg/PerformanceAnalytics/R/chart.RollingPerformance.R 2014-02-25 22:51:30 UTC (rev 3338) +++ pkg/PerformanceAnalytics/R/chart.RollingPerformance.R 2014-02-25 23:46:31 UTC (rev 3339) @@ -79,7 +79,7 @@ for(column in 1:columns) { # the drop=FALSE flag is essential for when the zoo object only has one column rollargs<-c(list(data=na.omit(x[,column,drop=FALSE])),funargs) - column.Return.calc <- do.call(xts:::rollapply.xts,rollargs) + column.Return.calc <- do.call(rollapply,rollargs) if(column == 1) Return.calc = xts(column.Return.calc) else Modified: pkg/PerformanceAnalytics/R/chart.TimeSeries.R =================================================================== --- pkg/PerformanceAnalytics/R/chart.TimeSeries.R 2014-02-25 22:51:30 UTC (rev 3338) +++ pkg/PerformanceAnalytics/R/chart.TimeSeries.R 2014-02-25 23:46:31 UTC (rev 3339) @@ -234,7 +234,7 @@ ) } # Needed for finding aligned dates for event lines and period areas - rownames = as.Date(xts:::time.xts(y)) + rownames = as.Date(time(y)) rownames = format(strptime(rownames,format = date.format.in), date.format) time.scale = periodicity(y)$scale Modified: pkg/PerformanceAnalytics/R/decomposeMVaR.R =================================================================== --- pkg/PerformanceAnalytics/R/decomposeMVaR.R 2014-02-25 22:51:30 UTC (rev 3338) +++ pkg/PerformanceAnalytics/R/decomposeMVaR.R 2014-02-25 23:46:31 UTC (rev 3339) @@ -4,28 +4,28 @@ { return(t(w)%*%sigma%*%w) } -PerformanceAnalytics:::portm2 +portm2 portm3 = function(w,M3) { return(t(w)%*%M3%*%(w%x%w)) } -PerformanceAnalytics:::portm3 +portm3 table.VaR.CornishFisher.portfolio = function (p, w, mu, sigma, M3, M4 , names) { w = matrix( w , ncol = 1 ) - alpha = PerformanceAnalytics:::.setalphaprob(p) + alpha = .setalphaprob(p) p = alpha z = qnorm(alpha) location = t(w) %*% mu pm2 = portm2(w, sigma) - dpm2 = as.vector(PerformanceAnalytics:::derportm2(w, sigma)) + dpm2 = as.vector(derportm2(w, sigma)) pm3 = portm3(w, M3) - dpm3 = as.vector(PerformanceAnalytics:::derportm3(w, M3)) - pm4 = PerformanceAnalytics:::portm4(w, M4) - dpm4 = as.vector(PerformanceAnalytics:::derportm4(w, M4)) + dpm3 = as.vector(derportm3(w, M3)) + pm4 = portm4(w, M4) + dpm4 = as.vector(derportm4(w, M4)) skew = pm3/pm2^(3/2) exkurt = pm4/pm2^(2) - 3 derskew = (2 * (pm2^(3/2)) * dpm3 - 3 * pm3 * sqrt(pm2) * From noreply at r-forge.r-project.org Wed Feb 26 01:20:00 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 26 Feb 2014 01:20:00 +0100 (CET) Subject: [Returnanalytics-commits] r3340 - pkg/PerformanceAnalytics/R Message-ID: <20140226002000.BF1CB1869C4@r-forge.r-project.org> Author: peter_carl Date: 2014-02-26 01:20:00 +0100 (Wed, 26 Feb 2014) New Revision: 3340 Modified: pkg/PerformanceAnalytics/R/chart.Boxplot.R Log: - really a reversion back to rev 2163 with hardcoded horizontal arg - anticipating future improvements that will make this work better Modified: pkg/PerformanceAnalytics/R/chart.Boxplot.R =================================================================== --- pkg/PerformanceAnalytics/R/chart.Boxplot.R 2014-02-25 23:46:31 UTC (rev 3339) +++ pkg/PerformanceAnalytics/R/chart.Boxplot.R 2014-02-26 00:20:00 UTC (rev 3340) @@ -12,7 +12,6 @@ #' #' @param R an xts, vector, matrix, data frame, timeSeries or zoo object of #' asset returns -#' @param horizontal TRUE/FALSE plot horizontal (TRUE) or vertical (FALSE) #' @param names logical. if TRUE, show the names of each series #' @param as.Tufte logical. default FALSE. if TRUE use method derived for Tufte #' for limiting chartjunk @@ -49,7 +48,7 @@ #' #' @export chart.Boxplot <- -function (R, horizontal = TRUE, names = TRUE, as.Tufte = FALSE, sort.by = c(NULL, "mean", "median", "variance"), colorset = "black", symbol.color = "red", mean.symbol = 1, median.symbol = "|", outlier.symbol = 1, show.data = NULL, add.mean = TRUE, sort.ascending = FALSE, xlab="Return", main = "Return Distribution Comparison", element.color = "darkgray", ...) +function (R, names = TRUE, as.Tufte = FALSE, sort.by = c(NULL, "mean", "median", "variance"), colorset = "black", symbol.color = "red", mean.symbol = 1, median.symbol = "|", outlier.symbol = 1, show.data = NULL, add.mean = TRUE, sort.ascending = FALSE, xlab="Return", main = "Return Distribution Comparison", element.color = "darkgray", ...) { # @author Peter Carl # DESCRIPTION: @@ -109,10 +108,10 @@ ) # end switch if(as.Tufte){ - boxplot(R[,column.order], horizontal = horizontal, names = names, main = main, xlab = xlab, ylab = "", pars = list(boxcol = "white", medlty = "blank", medpch = median.symbol, medlwd = 2, medcex = .8, medcol = colorset[column.order], whisklty = c(1,1), whiskcol = colorset[column.order], staplelty = "blank", outpch = outlier.symbol, outcex = .5, outcol = colorset[column.order] ), axes = FALSE, ...) + boxplot(R[,column.order], horizontal = TRUE, names = names, main = main, xlab = xlab, ylab = "", pars = list(boxcol = "white", medlty = "blank", medpch = median.symbol, medlwd = 2, medcex = .8, medcol = colorset[column.order], whisklty = c(1,1), whiskcol = colorset[column.order], staplelty = "blank", outpch = outlier.symbol, outcex = .5, outcol = colorset[column.order] ), axes = FALSE, ...) } else{ - boxplot(R[,column.order], horizontal = horizontal, names = names, main = main, xlab = xlab, ylab = "", pars = list(boxcol = colorset[column.order], medlwd = 1, medcol = colorset[column.order], whisklty = c(1,1), whiskcol = colorset[column.order], staplelty = 1, staplecol = colorset[column.order], staplecex = .5, outpch = outlier.symbol, outcex = .5, outcol = colorset[column.order] ), axes = FALSE, boxwex=.6, ...) + boxplot(R[,column.order], horizontal = TRUE, names = names, main = main, xlab = xlab, ylab = "", pars = list(boxcol = colorset[column.order], medlwd = 1, medcol = colorset[column.order], whisklty = c(1,1), whiskcol = colorset[column.order], staplelty = 1, staplecol = colorset[column.order], staplecex = .5, outpch = outlier.symbol, outcex = .5, outcol = colorset[column.order] ), axes = FALSE, boxwex=.6, ...) } # end else if(!is.null(show.data)) { From noreply at r-forge.r-project.org Wed Feb 26 01:28:23 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 26 Feb 2014 01:28:23 +0100 (CET) Subject: [Returnanalytics-commits] r3341 - pkg/PerformanceAnalytics/R Message-ID: <20140226002823.359BE186B27@r-forge.r-project.org> Author: braverock Date: 2014-02-26 01:28:22 +0100 (Wed, 26 Feb 2014) New Revision: 3341 Modified: pkg/PerformanceAnalytics/R/Return.portfolio.R Log: - revert calculation for geometric=TRUE in Return.portfolio to r2170, we'll improve this with a broader refactoring Modified: pkg/PerformanceAnalytics/R/Return.portfolio.R =================================================================== --- pkg/PerformanceAnalytics/R/Return.portfolio.R 2014-02-26 00:20:00 UTC (rev 3340) +++ pkg/PerformanceAnalytics/R/Return.portfolio.R 2014-02-26 00:28:22 UTC (rev 3341) @@ -180,16 +180,17 @@ for (col in colnames(weights)){ wealthindex.weighted[,col]=weights[,col]*wealthindex.assets[,col] } - wealthindex=reclass(apply(wealthindex.weighted,1,sum), R) - result = wealthindex - result[2:length(result)] = result[2:length(result)] / - lag(result)[2:length(result)] - 1 - #result[1] = result[1] - 1 - result[1] = result[1] / sum(abs(weights[1,])) -1 #divide by the sum of the first weighting vector to account for possible leverage - w = matrix(rep(NA), ncol(wealthindex.assets) * nrow(wealthindex.assets), ncol = ncol(wealthindex.assets), nrow = nrow(wealthindex.assets)) - w[1, ] = weights - w[2:length(wealthindex), ] = (wealthindex.weighted / rep(wealthindex, ncol(wealthindex.weighted)))[1:(length(wealthindex) - 1), ] - weightedreturns = R[, colnames(weights)] * w + wealthindex=apply(wealthindex.weighted,1,sum) + + # weighted cumulative returns + weightedcumcont=t(apply (wealthindex.assets,1, function(x,weights){ as.vector((x-1)* weights)},weights=weights)) + weightedreturns=diff(rbind(0,weightedcumcont)) # compound returns + colnames(weightedreturns)=colnames(wealthindex.assets) + if (!wealth.index){ + result=as.matrix(apply(weightedreturns,1,sum),ncol=1) + } else { + wealthindex=matrix(cumprod(1 + as.matrix(apply(weightedreturns,1, sum), ncol = 1)),ncol=1) + } } From noreply at r-forge.r-project.org Wed Feb 26 23:19:38 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 26 Feb 2014 23:19:38 +0100 (CET) Subject: [Returnanalytics-commits] r3342 - pkg/PerformanceAnalytics/man Message-ID: <20140226221938.B898E1864A8@r-forge.r-project.org> Author: braverock Date: 2014-02-26 23:19:38 +0100 (Wed, 26 Feb 2014) New Revision: 3342 Modified: pkg/PerformanceAnalytics/man/chart.Events.Rd Log: - update roxygen doc for chart.Events Modified: pkg/PerformanceAnalytics/man/chart.Events.Rd =================================================================== --- pkg/PerformanceAnalytics/man/chart.Events.Rd 2014-02-26 00:28:22 UTC (rev 3341) +++ pkg/PerformanceAnalytics/man/chart.Events.Rd 2014-02-26 22:19:38 UTC (rev 3342) @@ -52,9 +52,8 @@ \examples{ \dontrun{ data(managers) -R = PerformanceAnalytics:::Drawdowns(managers[,2,drop=FALSE]) n = table.Drawdowns(managers[,2,drop=FALSE]) -chart.Events(PerformanceAnalytics:::Drawdowns(managers[,2,drop=FALSE]), +chart.Events(Drawdowns(managers[,2,drop=FALSE]), dates = n$Trough, prior=max(na.omit(n$"To Trough")), post=max(na.omit(n$Recovery)), From noreply at r-forge.r-project.org Thu Feb 27 10:48:07 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 27 Feb 2014 10:48:07 +0100 (CET) Subject: [Returnanalytics-commits] r3343 - pkg/PerformanceAnalytics/tests/Examples Message-ID: <20140227094807.88057186852@r-forge.r-project.org> Author: braverock Date: 2014-02-27 10:48:07 +0100 (Thu, 27 Feb 2014) New Revision: 3343 Modified: pkg/PerformanceAnalytics/tests/Examples/PerformanceAnalytics-Ex.Rout.save Log: - update example output to account for Return.portfolio reversion Modified: pkg/PerformanceAnalytics/tests/Examples/PerformanceAnalytics-Ex.Rout.save =================================================================== --- pkg/PerformanceAnalytics/tests/Examples/PerformanceAnalytics-Ex.Rout.save 2014-02-26 22:19:38 UTC (rev 3342) +++ pkg/PerformanceAnalytics/tests/Examples/PerformanceAnalytics-Ex.Rout.save 2014-02-27 09:48:07 UTC (rev 3343) @@ -20,6 +20,18 @@ > pkgname <- "PerformanceAnalytics" > source(file.path(R.home("share"), "R", "examples-header.R")) > options(warn = 1) +> base::assign(".ExTimings", "PerformanceAnalytics-Ex.timings", pos = 'CheckExEnv') +> base::cat("name\tuser\tsystem\telapsed\n", file=base::get(".ExTimings", pos = 'CheckExEnv')) +> base::assign(".format_ptime", ++ function(x) { ++ if(!is.na(x[4L])) x[1L] <- x[1L] + x[4L] ++ if(!is.na(x[5L])) x[2L] <- x[2L] + x[5L] ++ options(OutDec = '.') ++ format(x[1L:3L], digits = 7L) ++ }, ++ pos = 'CheckExEnv') +> +> ### * > library('PerformanceAnalytics') Loading required package: zoo @@ -45,6 +57,7 @@ > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: ActiveReturn > ### Title: Active Premium or Active Return > ### Aliases: ActivePremium ActiveReturn @@ -72,12 +85,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("ActivePremium", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("AdjustedSharpeRatio") > ### * AdjustedSharpeRatio > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: AdjustedSharpeRatio > ### Title: Adjusted Sharpe ratio of the return distribution > ### Aliases: AdjustedSharpeRatio @@ -102,12 +118,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("AdjustedSharpeRatio", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("AppraisalRatio") > ### * AppraisalRatio > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: AppraisalRatio > ### Title: Appraisal ratio of the return distribution > ### Aliases: AppraisalRatio @@ -132,12 +151,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("AppraisalRatio", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("BernardoLedoitRatio") > ### * BernardoLedoitRatio > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: BernardoLedoitRatio > ### Title: Bernardo and Ledoit ratio of the return distribution > ### Aliases: BernardoLedoitRatio @@ -160,12 +182,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("BernardoLedoitRatio", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("BetaCoMoments") > ### * BetaCoMoments > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: BetaCoMoments > ### Title: Functions to calculate systematic or beta co-moments of return > ### series @@ -197,12 +222,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("BetaCoMoments", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("BurkeRatio") > ### * BurkeRatio > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: BurkeRatio > ### Title: Burke ratio of the return distribution > ### Aliases: BurkeRatio @@ -234,12 +262,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("BurkeRatio", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("CAPM.RiskPremium") > ### * CAPM.RiskPremium > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: CAPM.CML.slope > ### Title: utility functions for single factor (CAPM) CML, SML, and > ### RiskPremium @@ -269,12 +300,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("CAPM.RiskPremium", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("CAPM.alpha") > ### * CAPM.alpha > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: CAPM.alpha > ### Title: calculate single factor model (CAPM) alpha > ### Aliases: CAPM.alpha SFM.alpha @@ -327,12 +361,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("CAPM.alpha", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("CAPM.beta") > ### * CAPM.beta > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: CAPM.beta > ### Title: calculate single factor model (CAPM) beta > ### Aliases: CAPM.beta CAPM.beta.bear CAPM.beta.bull SFM.beta TimingRatio @@ -405,12 +442,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("CAPM.beta", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("CAPM.dynamic") > ### * CAPM.dynamic > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: CAPM.dynamic > ### Title: Time-varying conditional single factor model beta > ### Aliases: CAPM.dynamic SFM.dynamic @@ -493,12 +533,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("CAPM.dynamic", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("CAPM.epsilon") > ### * CAPM.epsilon > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: CAPM.epsilon > ### Title: Regression epsilon of the return distribution > ### Aliases: CAPM.epsilon SFM.epsilon @@ -521,12 +564,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("CAPM.epsilon", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("CAPM.jensenAlpha") > ### * CAPM.jensenAlpha > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: CAPM.jensenAlpha > ### Title: Jensen's alpha of the return distribution > ### Aliases: CAPM.jensenAlpha SFM.jensenAlpha @@ -547,12 +593,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("CAPM.jensenAlpha", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("CDD") > ### * CDD > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: CDD > ### Title: Calculate Uryasev's proposed Conditional Drawdown at Risk (CDD > ### or CDaR) measure @@ -580,12 +629,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("CDD", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("CalmarRatio") > ### * CalmarRatio > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: CalmarRatio > ### Title: calculate a Calmar or Sterling reward/risk ratio > ### Aliases: CalmarRatio SterlingRatio @@ -611,12 +663,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("CalmarRatio", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("CoMoments") > ### * CoMoments > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: CoMoments > ### Title: Functions for calculating comoments of financial time series > ### Aliases: CoKurtosis CoMoments CoSkewness CoVariance @@ -634,12 +689,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("CoMoments", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("DRatio") > ### * DRatio > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: DRatio > ### Title: d ratio of the return distribution > ### Aliases: DRatio @@ -662,12 +720,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("DRatio", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("DownsideDeviation") > ### * DownsideDeviation > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: DownsideDeviation > ### Title: downside risk (deviation, variance) of the return distribution > ### Aliases: DownsideDeviation DownsidePotential SemiDeviation SemiVariance @@ -715,12 +776,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("DownsideDeviation", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("DownsideFrequency") > ### * DownsideFrequency > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: DownsideFrequency > ### Title: downside frequency of the return distribution > ### Aliases: DownsideFrequency @@ -744,12 +808,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("DownsideFrequency", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("ES") > ### * ES > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: ETL > ### Title: calculates Expected Shortfall(ES) (or Conditional > ### Value-at-Risk(CVaR) for univariate and component, using a variety of @@ -860,6 +927,8 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("ES", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() detaching ?package:robustbase? @@ -869,6 +938,7 @@ > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: FamaBeta > ### Title: Fama beta of the return distribution > ### Aliases: FamaBeta @@ -891,12 +961,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("FamaBeta", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("Frequency") > ### * Frequency > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: Frequency > ### Title: Frequency of the return distribution > ### Aliases: Frequency @@ -914,12 +987,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("Frequency", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("InformationRatio") > ### * InformationRatio > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: InformationRatio > ### Title: InformationRatio = ActivePremium/TrackingError > ### Aliases: InformationRatio @@ -945,12 +1021,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("InformationRatio", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("Kappa") > ### * Kappa > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: Kappa > ### Title: Kappa of the return distribution > ### Aliases: Kappa @@ -977,12 +1056,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("Kappa", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("KellyRatio") > ### * KellyRatio > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: KellyRatio > ### Title: calculate Kelly criterion ratio (leverage or bet size) for a > ### strategy @@ -1004,12 +1086,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("KellyRatio", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("M2Sortino") > ### * M2Sortino > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: M2Sortino > ### Title: M squared for Sortino of the return distribution > ### Aliases: M2Sortino @@ -1034,12 +1119,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("M2Sortino", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("MSquared") > ### * MSquared > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: MSquared > ### Title: M squared of the return distribution > ### Aliases: MSquared @@ -1062,12 +1150,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("MSquared", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("MSquaredExcess") > ### * MSquaredExcess > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: MSquaredExcess > ### Title: M squared excess of the return distribution > ### Aliases: MSquaredExcess @@ -1094,12 +1185,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("MSquaredExcess", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("MarketTiming") > ### * MarketTiming > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: MarketTiming > ### Title: Market timing models > ### Aliases: MarketTiming @@ -1135,12 +1229,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("MarketTiming", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("MartinRatio") > ### * MartinRatio > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: MartinRatio > ### Title: Martin ratio of the return distribution > ### Aliases: MartinRatio @@ -1165,12 +1262,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("MartinRatio", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("MeanAbsoluteDeviation") > ### * MeanAbsoluteDeviation > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: MeanAbsoluteDeviation > ### Title: Mean absolute deviation of the return distribution > ### Aliases: MeanAbsoluteDeviation @@ -1193,12 +1293,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("MeanAbsoluteDeviation", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("Modigliani") > ### * Modigliani > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: Modigliani > ### Title: Modigliani-Modigliani measure > ### Aliases: Modigliani @@ -1223,12 +1326,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("Modigliani", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("NetSelectivity") > ### * NetSelectivity > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: NetSelectivity > ### Title: Net selectivity of the return distribution > ### Aliases: NetSelectivity @@ -1251,12 +1357,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("NetSelectivity", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("Omega") > ### * Omega > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: Omega > ### Title: calculate Omega for a return series > ### Aliases: Omega @@ -1423,12 +1532,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("Omega", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("OmegaExcessReturn") > ### * OmegaExcessReturn > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: OmegaExcessReturn > ### Title: Omega excess return of the return distribution > ### Aliases: OmegaExcessReturn OmegaExessReturn @@ -1451,12 +1563,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("OmegaExcessReturn", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("OmegaSharpeRatio") > ### * OmegaSharpeRatio > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: OmegaSharpeRatio > ### Title: Omega-Sharpe ratio of the return distribution > ### Aliases: OmegaSharpeRatio @@ -1481,12 +1596,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("OmegaSharpeRatio", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("PainIndex") > ### * PainIndex > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: PainIndex > ### Title: Pain index of the return distribution > ### Aliases: PainIndex @@ -1511,12 +1629,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("PainIndex", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("PainRatio") > ### * PainRatio > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: PainRatio > ### Title: Pain ratio of the return distribution > ### Aliases: PainRatio @@ -1541,12 +1662,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("PainRatio", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("ProspectRatio") > ### * ProspectRatio > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: ProspectRatio > ### Title: Prospect ratio of the return distribution > ### Aliases: ProspectRatio @@ -1571,12 +1695,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("ProspectRatio", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("Return.Geltner") > ### * Return.Geltner > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: Return.Geltner > ### Title: calculate Geltner liquidity-adjusted return series > ### Aliases: Return.Geltner @@ -1610,12 +1737,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("Return.Geltner", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("Return.annualized") > ### * Return.annualized > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: Return.annualized > ### Title: calculate an annualized return for comparing instruments with > ### different length history @@ -1641,12 +1771,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("Return.annualized", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("Return.annualized.excess") > ### * Return.annualized.excess > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: Return.annualized.excess > ### Title: calculates an annualized excess return for comparing instruments > ### with different length history @@ -1662,12 +1795,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("Return.annualized.excess", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("Return.calculate") > ### * Return.calculate > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: Return.calculate > ### Title: calculate simple or compound returns from prices > ### Aliases: CalculateReturns Return.calculate @@ -3703,12 +3839,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("Return.calculate", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("Return.clean") > ### * Return.clean > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: Return.clean > ### Title: clean returns in a time series to to provide more robust risk > ### estimates @@ -3744,6 +3883,8 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("Return.clean", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() detaching ?package:robustbase? @@ -3753,6 +3894,7 @@ > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: Return.cumulative > ### Title: calculate a compounded (geometric) cumulative return > ### Aliases: Return.cumulative @@ -3775,12 +3917,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("Return.cumulative", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("Return.excess") > ### * Return.excess > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: Return.excess > ### Title: Calculates the returns of an asset in excess of the given risk > ### free rate @@ -3832,12 +3977,15 @@ > > > +> base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") +> base::cat("Return.excess", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") > cleanEx() > nameEx("Return.portfolio") > ### * Return.portfolio > > flush(stderr()); flush(stdout()) > +> base::assign(".ptime", proc.time(), pos = "CheckExEnv") > ### Name: Return.rebalancing > ### Title: Calculates weighted returns for a portfolio of assets > ### Aliases: Return.portfolio Return.rebalancing @@ -3854,1056 +4002,1059 @@ weighting vector is null, calulating an equal weighted portfolio portfolio.returns 1997-01-31 0.0262 -1997-02-28 0.0172 -1997-03-31 0.0043 -1997-04-30 0.0043 -1997-05-31 0.0132 -1997-06-30 0.0208 -1997-07-31 0.0301 +1997-02-28 0.0177 +1997-03-31 0.0045 +1997-04-30 0.0045 +1997-05-31 0.0139 +1997-06-30 0.0222 +1997-07-31 0.0327 1997-08-31 -0.0001 -1997-09-30 0.0223 -1997-10-31 -0.0015 -1997-11-30 0.0043 -1997-12-31 0.0134 -1998-01-31 0.0008 -1998-02-28 0.0186 -1998-03-31 0.0279 -1998-04-30 0.0114 -1998-05-31 0.0060 +1997-09-30 0.0250 +1997-10-31 -0.0018 +1997-11-30 0.0050 +1997-12-31 0.0154 +1998-01-31 0.0009 +1998-02-28 0.0217 +1998-03-31 0.0331 +1998-04-30 0.0139 +1998-05-31 0.0075 1998-06-30 0.0000 -1998-07-31 0.0039 -1998-08-31 -0.0230 -1998-09-30 -0.0074 -1998-10-31 -0.0174 -1998-11-30 0.0100 -1998-12-31 0.0125 -1999-01-31 0.0058 -1999-02-28 0.0082 -1999-03-31 0.0123 -1999-04-30 0.0244 -1999-05-31 0.0091 -1999-06-30 0.0196 -1999-07-31 0.0077 -1999-08-31 0.0039 -1999-09-30 0.0087 -1999-10-31 0.0051 -1999-11-30 0.0175 -1999-12-31 0.0290 -2000-01-31 0.0126 -2000-02-29 0.0260 -2000-03-31 0.0060 -2000-04-30 -0.0038 -2000-05-31 0.0017 -2000-06-30 0.0124 -2000-07-31 0.0062 -2000-08-31 0.0145 -2000-09-30 0.0029 -2000-10-31 0.0006 -2000-11-30 0.0051 -2000-12-31 0.0173 -2001-01-31 0.0200 -2001-02-28 0.0050 -2001-03-31 0.0050 -2001-04-30 0.0006 -2001-05-31 0.0098 -2001-06-30 0.0044 -2001-07-31 0.0010 -2001-08-31 0.0099 -2001-09-30 -0.0052 -2001-10-31 0.0114 -2001-11-30 0.0006 -2001-12-31 0.0077 -2002-01-31 0.0097 -2002-02-28 -0.0006 -2002-03-31 0.0065 -2002-04-30 0.0083 -2002-05-31 0.0074 -2002-06-30 -0.0021 -2002-07-31 -0.0071 -2002-08-31 0.0067 -2002-09-30 0.0040 -2002-10-31 -0.0035 -2002-11-30 0.0068 -2002-12-31 0.0136 -2003-01-31 0.0143 -2003-02-28 0.0087 -2003-03-31 -0.0019 -2003-04-30 0.0120 -2003-05-31 0.0215 -2003-06-30 0.0059 -2003-07-31 -0.0006 -2003-08-31 0.0078 -2003-09-30 0.0132 -2003-10-31 0.0117 -2003-11-30 0.0070 -2003-12-31 0.0164 -2004-01-31 0.0156 -2004-02-29 0.0127 -2004-03-31 0.0032 -2004-04-30 -0.0075 -2004-05-31 -0.0052 -2004-06-30 0.0014 -2004-07-31 -0.0002 -2004-08-31 0.0024 -2004-09-30 0.0082 -2004-10-31 0.0087 -2004-11-30 0.0201 -2004-12-31 0.0103 -2005-01-31 -0.0001 -2005-02-28 0.0121 -2005-03-31 -0.0026 -2005-04-30 -0.0102 -2005-05-31 0.0022 -2005-06-30 0.0120 -2005-07-31 0.0132 -2005-08-31 0.0094 -2005-09-30 0.0156 -2005-10-31 -0.0078 -2005-11-30 0.0120 -2005-12-31 0.0121 -2006-01-31 0.0250 -2006-02-28 0.0048 -2006-03-31 0.0141 -2006-04-30 0.0179 -2006-05-31 -0.0065 -2006-06-30 -0.0007 -2006-07-31 0.0015 -2006-08-31 0.0058 -2006-09-30 0.0003 -2006-10-31 0.0123 -2006-11-30 0.0154 -2006-12-31 0.0149 -2007-01-31 0.0114 -2007-02-28 0.0098 -2007-03-31 0.0078 -2007-04-30 0.0143 -2007-05-31 0.0169 -2007-06-30 0.0082 -2007-07-31 0.0038 -2007-08-31 -0.0135 -2007-09-30 0.0204 -2007-10-31 0.0240 -2007-11-30 -0.0110 -2007-12-31 0.0040 -2008-01-31 -0.0151 -2008-02-29 0.0150 -2008-03-31 -0.0177 -2008-04-30 0.0088 -2008-05-31 0.0140 -2008-06-30 -0.0017 -2008-07-31 -0.0178 -2008-08-31 -0.0108 -2008-09-30 -0.0501 [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3343 From noreply at r-forge.r-project.org Thu Feb 27 11:39:11 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 27 Feb 2014 11:39:11 +0100 (CET) Subject: [Returnanalytics-commits] r3344 - pkg/Meucci Message-ID: <20140227103911.C3FEA180009@r-forge.r-project.org> Author: braverock Date: 2014-02-27 11:39:11 +0100 (Thu, 27 Feb 2014) New Revision: 3344 Removed: pkg/Meucci/inst/ Modified: pkg/Meucci/DESCRIPTION Log: - Add Attilio and David to Authors field - David Ardia is now the maintainer - bump version Modified: pkg/Meucci/DESCRIPTION =================================================================== --- pkg/Meucci/DESCRIPTION 2014-02-27 09:48:07 UTC (rev 3343) +++ pkg/Meucci/DESCRIPTION 2014-02-27 10:39:11 UTC (rev 3344) @@ -2,10 +2,11 @@ Type: Package Title: Collection of functionality ported from the MATLAB code of Attilio Meucci. -Version: 0.2.2 +Version: 0.3 Date: $Date: 2012-06-06 15:18:48 -0500 (Wed, 06 Jun 2012) $ -Author: Ram Ahluwalia, Manan Shah, Xavier Valls -Maintainer: Brian G. Peterson +Author: + Attilio Meucci, Ram Ahluwalia, David Ardia, Xavier Valls, Brian Peterson, Manan Shah +Maintainer: "David Ardia" Description: Attilio Meucci is a thought leader in advanced risk and portfolio management. His innovations include Entropy Pooling (technique for fully flexible portfolio construction), Factors on Demand (on-the-fly factor @@ -53,56 +54,4 @@ PerformanceAnalytics License: GPL URL: http://r-forge.r-project.org/projects/returnanalytics/ -Copyright: (c) 2012 -Collate: - 'CmaCopula.R' - 'DetectOutliersviaMVE.R' - 'EntropyProg.R' - 'FullyFlexibleBayesNets.R' - 'HermiteGrid.R' - 'InvariantProjection.R' - 'logToArithmeticCovariance.R' - 'MeanDiversificationFrontier.R' - 'MultivariateOUnCointegration.R' - 'Prior2Posterior.R' - 'RobustBayesianAllocation.R' - 'LognormalMoments2Parameters.R' - 'LognormalParameters2Statistics.R' - 'LognormalCopulaPdf.R' - 'NormalCopulaPdf.R' - 'StudentTCopulaPdf.R' - 'ConvertChangeInYield2Price.R' - 'ProjectionStudentT.R' - 'TwoDimEllipsoid.R' - 'PerformIidAnalysis.R' - 'SimulateJumpDiffusionMerton.R' - 'BlackScholesCallPrice.R' - 'InterExtrapolate.R' - 'CentralAndStandardizedStatistics.R' - 'FitExpectationMaximization.R' - 'QuantileMixture.R' - 'GenerateUniformDrawsOnUnitSphere.R' - 'PlotMarginalsNormalInverseWishart.R' - 'RandNormalInverseWishart.R' - 'FitMultivariateGarch.R' - 'MvnRnd.R' - 'MleRecursionForStudentT.R' - 'CovertCompoundedReturns2Price.R' - 'MaxRsqCS.R' - 'EfficientFrontierReturnsBenchmark.R' - 'EfficientFrontierReturns.R' - 'EfficientFrontierPrices.R' - 'FitOrnsteinUhlenbeck.R' - 'PlotVolVsCompositionEfficientFrontier.R' - 'BlackLittermanFormula.R' - 'Log2Lin.R' - 'PlotCompositionEfficientFrontier.R' - 'MaxRsqTS.R' - 'PlotDistributions.R' - 'DoubleDecay.R' - 'Fit2Moms.R' - 'LeastInfoKernel.R' - 'data.R' - 'ButterflyTradingFunctions.R' - 'RankingInformationFunctions.R' - 'pHistPriorPosterior.R' +Copyright: (c) 2014