[Returnanalytics-commits] r3306 - in pkg/PortfolioAnalytics: . R man

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Mon Feb 10 00:55:33 CET 2014


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}}
+}
+



More information about the Returnanalytics-commits mailing list