name.replace <- function(rnames){
rnames<-gsub("objective_measures.",'',rnames)
matchvec<-c('mean.mean','median.median','ES.ES','ETL.ETL','CVaR.ES','ES.MES','ETL.MES','CVaR.MES','VaR.MVaR','maxDrawdown.maxDrawdown','sd.sd','StdDev.StdDev')
for(str in matchvec){
pos<-pmatch(str,rnames)
if(!is.na(pos)){
switch(str,
mean.mean = {rnames[pos]<-'mean'},
median.median = {rnames[pos]<-'median'},
CVaR.MES =, CVaR.ES = {rnames[pos]<-'CVaR'},
ES.MES =, ES.ES = {rnames[pos]<-'ES'},
ETL.MES =, ETL.ETL = {rnames[pos]<-'ETL'},
VaR.MVaR = {rnames[pos]<-'VaR'},
maxDrawdown.maxDrawdown = {rnames[pos]<-'maxDrawdown'},
sd.sd=, StdDev.StdDev = {rnames[pos]<-'StdDev'},
)
}
}
return(rnames)
}
extractStats <- function (object, prefix=NULL, ...){
UseMethod('extractStats')
}
extractStats.optimize.portfolio.DEoptim <- function(object, prefix=NULL, ...) {
if(!inherits(object, "optimize.portfolio.DEoptim")) stop("object must be of class optimize.portfolio.DEoptim")
if(is.null(object$DEoptim_objective_results)) stop("DEoptim_objective_results is null, trace=TRUE must be specified in optimize.portfolio")
trow<-c(unlist(object$objective_measures),out=object$out,object$weights)
result<-trow
l = length(object$DEoptim_objective_results)
nobj<-length(unlist(object$DEoptim_objective_results[[1]]$objective_measures))
result=matrix(nrow=l,ncol=(nobj+length(object$weights))+1)
ncols<-ncol(result)
for (i in 1:l) {
if(!is.atomic(object$DEoptim_objective_results[[i]])) {
result[i,1:nobj]<-unlist(object$DEoptim_objective_results[[i]]$objective_measures)
result[i,(nobj+1)]<-object$DEoptim_objective_results[[i]]$out
result[i,(nobj+2):ncols]<-object$DEoptim_objective_results[[i]]$weights
}
}
rnames<-c(names(unlist(object$DEoptim_objective_results[[1]]$objective_measures)),'out',paste('w',names(object$weights),sep='.'))
rnames<-name.replace(rnames)
colnames(result)<-rnames
rownames(result) = paste(prefix,"DE.portf", index(object$DEoptim_objective_results), sep=".")
return(result)
}
extractStats.optimize.portfolio.ROI <- function(object, prefix=NULL, ...) {
if(!inherits(object, "optimize.portfolio.ROI")) stop("object must be of class optimize.portfolio.ROI")
trow <- c(object$out, object$weights)
objmeas <- extractObjectiveMeasures(object)
objnames <- names(objmeas)
obj <- unlist(objmeas)
result <- c(obj, trow)
rnames<-c(objnames, 'out', paste('w', names(object$weights), sep='.'))
names(result)<-rnames
return(result)
}
extractStats.optimize.portfolio.CVXR <- function(object, prefix=NULL, ...) {
if(!inherits(object, "optimize.portfolio.CVXR")) stop("object must be of class optimize.portfolio.CVXR")
trow <- c(object$out, object$weights)
objmeas <- extractObjectiveMeasures(object)
objnames <- names(objmeas)
obj <- unlist(objmeas)
result <- c(obj, trow)
rnames<-c(objnames, 'out', paste('w', names(object$weights), sep='.'))
names(result)<-rnames
return(result)
}
extractStats.optimize.portfolio.pso <- function(object, prefix=NULL, ...){
if(!inherits(object, "optimize.portfolio.pso")) stop("object must be of class optimize.portfolio.pso")
if(is.null(object$PSOoutput)) stop("PSOoutput is null, trace=TRUE must be specified in optimize.portfolio")
R <- object$R
portfolio <- object$portfolio
normalize_weights <- function(weights){
if(!is.null(constraints$min_sum) | !is.null(constraints$max_sum)){
if(!is.null(constraints$max_sum) & constraints$max_sum != Inf ) {
max_sum=constraints$max_sum
if(sum(weights)>max_sum) { weights<-(max_sum/sum(weights))*weights }
}
if(!is.null(constraints$min_sum) & constraints$min_sum != -Inf ) {
min_sum=constraints$min_sum
if(sum(weights)<min_sum) { weights<-(min_sum/sum(weights))*weights }
}
}
return(weights)
}
constraints <- get_constraints(object$portfolio)
psoweights <- do.call(rbind, lapply(object$PSOoutput$stats$x, t))
psoweights <- t(apply(psoweights, 1, normalize_weights))
psoweights <- rbind(object$weights, psoweights)
tmpout <- unlist(object$PSOoutput$stats$f)
tmpout <- c(object$out, tmpout)
stopifnot("package:foreach" %in% search() || suppressMessages(requireNamespace("foreach",quietly = TRUE)))
i <- 1
obj <- foreach::foreach(i=1:nrow(psoweights), .inorder=TRUE, .combine=rbind, .errorhandling='remove') %dopar% {
unlist(constrained_objective(w=psoweights[i,], R=R, portfolio=portfolio, trace=TRUE)$objective_measures)
}
objnames <- name.replace(colnames(obj))
result <- cbind(obj, tmpout, psoweights)
colnames(result) <- c(objnames, "out", paste('w',names(object$weights),sep='.'))
rownames(result) <- paste(prefix, "pso.portf", index(tmpout), sep=".")
return(result)
}
extractStats.optimize.portfolio.GenSA <- function(object, prefix=NULL, ...) {
if(!inherits(object, "optimize.portfolio.GenSA")) stop("object must be of class optimize.portfolio.GenSA")
if(is.null(object$GenSAoutput)) stop("GenSAoutput is null, trace=TRUE must be specified in optimize.portfolio")
trow<-c(out=object$out, object$weights)
obj <- unlist(object$objective_measures)
result <- c(obj, trow)
rnames <- name.replace(names(result))
names(result) <- rnames
return(result)
}
extractStats.optimize.portfolio.invol <- function(object, prefix=NULL, ...) {
if(!inherits(object, "optimize.portfolio.invol")) stop("object must be of class optimize.portfolio.invol")
trow<-c(out=object$out, object$weights)
obj <- unlist(object$objective_measures)
result <- c(obj, trow)
rnames <- name.replace(names(result))
names(result) <- rnames
return(result)
}
extractStats.optimize.portfolio.eqwt <- function(object, prefix=NULL, ...) {
if(!inherits(object, "optimize.portfolio.eqwt")) stop("object must be of class optimize.portfolio.eqwt")
trow<-c(out=object$out, object$weights)
obj <- unlist(object$objective_measures)
result <- c(obj, trow)
rnames <- name.replace(names(result))
names(result) <- rnames
return(result)
}
extractStats.optimize.portfolio.rebalancing <- function(object, prefix=NULL, ...) {
if(!inherits(object, "optimize.portfolio.rebalancing")) stop("object must be of class optimize.portfolio.rebalancing")
if(inherits(object$portfolio, "regime.portfolios")){
return(extractStatsRegime(object, prefix=prefix))
} else {
return(lapply(object$opt_rebal, extractStats, ...))
}
}
extractStatsRegime <- function(object, prefix=NULL){
tmp.regimes <- unlist(lapply(object$opt_rebalancing, function(x) x$regime))
unique.regimes <- unique(tmp.regimes)
out.list <- vector("list", length(unique.regimes))
names(out.list) <- paste("regime", 1:length(unique.regimes), sep=".")
for(i in 1:length(unique.regimes)){
tmp.idx <- which(tmp.regimes == unique.regimes[i])
tmp <- vector("list", length(tmp.idx))
for(j in 1:length(tmp)){
tmp[[j]] <- extractStats(object$opt_rebalancing[[tmp.idx[j]]], prefix=prefix)
}
out.list[[i]] <- tmp
}
out.list
}
extractStats.optimize.portfolio.parallel <- function(object,prefix=NULL,...) {
resultlist<-object
l = length(resultlist)
result=NULL
for (i in 1:l) {
if(is.null(result)) result<-extractStats(resultlist[[i]])
else result <- rbind(result,extractStats(resultlist[[i]]))
}
rownames(result) = paste("par", index(result), rownames(result), sep=".")
return(result)
}
extractStats.optimize.portfolio.random <- function(object, prefix=NULL, ...){
if(!inherits(object, "optimize.portfolio.random")) stop("object must be of class optimize.portfolio.random")
if(is.null(object$random_portfolio_objective_results)) stop("random_portfolio_objective_results is null, trace=TRUE must be specified in optimize.portfolio")
OptimResults<-object
l = length(OptimResults$random_portfolio_objective_results)
nobj<-length(unlist(OptimResults$random_portfolio_objective_results[[1]]$objective_measures))
result=matrix(nrow=l,ncol=(nobj+length(OptimResults$weights))+1)
ncols<-ncol(result)
for (i in 1:l) {
if(!is.atomic(OptimResults$random_portfolio_objective_results[[i]])) {
result[i,1:nobj]<-unlist(OptimResults$random_portfolio_objective_results[[i]]$objective_measures)
result[i,(nobj+1)]<-OptimResults$random_portfolio_objective_results[[i]]$out
result[i,(nobj+2):ncols]<-OptimResults$random_portfolio_objective_results[[i]]$weights
}
}
rnames<-c(names(unlist(OptimResults$random_portfolio_objective_results[[1]]$objective_measures)),'out',paste('w',names(OptimResults$weights),sep='.'))
rnames<-name.replace(rnames)
colnames(result)<-rnames
rownames(result) = paste(prefix,"rnd.portf", index(OptimResults$random_portfolio_objective_results), sep=".")
return(result)
}
extractStats.opt.list <- function(object, ...){
stats_list <- vector("list", length(object))
for(i in 1:length(stats_list)){
stats_list[[i]] <- extractStats(object[[i]])
}
return(stats_list)
}
extractStats.opt.rebal.list <- function(object, ...){
stats_list <- vector("list", length(object))
for(i in 1:length(stats_list)){
stats_list[[i]] <- extractStats(object[[i]])
}
return(stats_list)
}
extractWeights <- function (object, ...){
UseMethod('extractWeights')
}
extractWeights.optimize.portfolio <- function(object, ...){
if(!inherits(object, "optimize.portfolio")){
stop("object must be of class 'optimize.portfolio'")
}
return(object$weights)
}
extractWeights.optimize.portfolio.rebalancing <- function(object, ...){
if(!inherits(object, "optimize.portfolio.rebalancing")){
stop("Object passed in must be of class 'optimize.portfolio.rebalancing'")
}
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(rebal_object[[i]]$weights)
colnames(result) = names(unlist(rebal_object[[1]]$weights))
rownames(result) = names(rebal_object)
result = as.xts(result, dateFormat="Date")
return(result)
}
extractWeights.summary.optimize.portfolio.rebalancing <- function(object, ...){
object$weights
}
extractWeights.opt.list <- function(object, ...){
weights_list <- list()
for(i in 1:length(object)){
weights_list[[i]] <- object[[i]]$weights
}
opt_names <- names(object)
if(is.null(opt_names)) opt_names <- paste("opt", 1:length(object))
weights_names <- unlist(lapply(weights_list, names))
names_unique <- unique(weights_names)
weights_mat <- matrix(0, nrow=length(weights_list), ncol=length(names_unique),
dimnames=list(opt_names, names_unique))
for(i in 1:length(weights_list)){
pm <- pmatch(x=names(weights_list[[i]]), table=names_unique)
weights_mat[i, pm] <- weights_list[[i]]
}
return(weights_mat)
}
extractWeights.opt.rebal.list <- function(object, ...){
weights_list <- vector("list", length(object))
for(i in 1:length(weights_list)){
weights_list[[i]] <- extractWeights(object[[i]])
}
return(weights_list)
}
extractObjectiveMeasures <- function(object){
UseMethod("extractObjectiveMeasures")
}
extractObjectiveMeasures.optimize.portfolio <- function(object){
if(!inherits(object, "optimize.portfolio")) stop("object must be of class 'optimize.portfolio'")
out <- object$objective_measures
return(out)
}
extractObjectiveMeasures.optimize.portfolio.rebalancing <- function(object){
if(!inherits(object, "optimize.portfolio.rebalancing")) stop("object must be of class 'optimize.portfolio.rebalancing'")
if(inherits(object$portfolio, "regime.portfolios")){
result <- extractObjRegime(object)
} else {
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(rebal_object[[i]]))
}
colnames(result) <- name.replace(names(unlist(extractObjectiveMeasures(rebal_object[[1]]))))
rownames(result) <- names(rebal_object)
result <- as.xts(result)
}
return(result)
}
extractObjRegime <- function(object){
tmp.regimes <- unlist(lapply(object$opt_rebalancing, function(x) x$regime))
unique.regimes <- sort(unique(tmp.regimes))
out.list <- vector("list", length(unique.regimes))
names(out.list) <- paste("regime", unique.regimes, sep=".")
for(i in 1:length(unique.regimes)){
tmp.idx <- which(tmp.regimes == unique.regimes[i])
tmp <- vector("list", length(tmp.idx))
for(j in 1:length(tmp)){
tmp[[j]] <- unlist(object$opt_rebalancing[[tmp.idx[j]]]$objective_measures)
}
obj <- do.call(rbind, tmp)
colnames(obj) <- name.replace(colnames(obj))
obj <- xts(obj, as.Date(names(tmp.idx)))
out.list[[unique.regimes[i]]] <- obj
}
out.list
}
extractObjectiveMeasures.summary.optimize.portfolio.rebalancing <- function(object){
object$objective_measures
}
extractObjectiveMeasures.opt.list <- function(object){
if(!inherits(object, "opt.list")) stop("object must be of class 'opt.list'")
opt.names <- names(object)
if(is.null(opt.names)) opt.names <- paste("portfolio", 1:length(object))
base <- sapply(object[[1]]$portfolio$objectives, function(x) paste(class(x)[1], x$name, sep="."))
obj_list <- lapply(object, function(x) sapply(x$portfolio$objectives, function(u) paste(class(u)[1], u$name, sep=".")))
if(all(sapply(obj_list, function(u) identical(x=base, y=u)))){
obj_list <- list()
for(i in 1:length(object)){
tmp <- unlist(object[[i]]$objective_measures)
names(tmp) <- name.replace(names(tmp))
obj_list[[opt.names[i]]] <- tmp
}
obj_names <- unique(unlist(lapply(obj_list, names)))
obj_mat <- matrix(NA, nrow=length(obj_list), ncol=length(obj_names),
dimnames=list(opt.names, obj_names))
for(i in 1:length(obj_list)){
pm <- pmatch(x=names(obj_list[[i]]), table=obj_names)
obj_mat[i, pm] <- obj_list[[i]]
}
out <- obj_mat
} else {
tmp.obj <- list()
tmp.budget <- list()
for(i in 1:length(object)){
tmp.portf <- object[[i]]$portfolio
for(j in 1:length(tmp.portf$objectives)){
if(inherits(tmp.portf$objectives[[j]], "risk_budget_objective")){
num.budget <- length(tmp.budget) + 1
tmp.budget[[num.budget]] <- tmp.portf$objectives[[j]]
} else {
num.obj <- length(tmp.obj) + 1
tmp.obj[[num.obj]] <- tmp.portf$objectives[[j]]
}
}
}
tmp.obj <- c(tmp.obj, tmp.budget)
out.obj <- list()
obj.names <- sapply(tmp.obj, function(x) paste(x$name, class(x)[1], sep="."))
if(any(duplicated(obj.names))){
idx <- which(!duplicated(obj.names, fromLast=TRUE))
for(i in 1:length(idx)){
out.obj[[i]] <- tmp.obj[[idx[i]]]
}
}
out <- list()
for(i in 1:length(object)){
object[[i]]$portfolio$objectives <- tmp.obj
tmp.weights <- object[[i]]$weights
tmp.R <- object[[i]]$R
tmp.portf <- object[[i]]$portfolio
tmp <- unlist(constrained_objective(w=tmp.weights, R=tmp.R, portfolio=tmp.portf, trace=TRUE)$objective_measures)
names(tmp) <- name.replace(names(tmp))
out[[opt.names[i]]] <- tmp
}
out <- do.call(rbind, out)
}
return(out)
}
extractObjectiveMeasures.opt.rebal.list <- function(object, ...){
obj_list <- vector("list", length(object))
for(i in 1:length(obj_list)){
obj_list[[i]] <- extractObjectiveMeasures(object[[i]])
}
return(obj_list)
}
extractGroups <- function(object, ...){
if(!inherits(object, "optimize.portfolio")) stop("object must be of class 'optimize.portfolio'")
category_labels <- object$portfolio$category_labels
constraints <- get_constraints(object$portfolio)
groups <- constraints$groups
cat_weights <- NULL
group_weights <- NULL
if(!is.null(category_labels)){
cat_names <- names(category_labels)
ncats <- length(category_labels)
cat_weights <- rep(0, ncats)
for(i in 1:ncats){
cat_weights[i] <- sum(object$weights[category_labels[[i]]])
}
names(cat_weights) <- cat_names
}
if(!is.null(groups)){
n.groups <- length(groups)
group_weights <- rep(0, n.groups)
for(i in 1:n.groups){
group_weights[i] <- sum(object$weights[groups[[i]]])
}
names(group_weights) <- constraints$group_labels
}
return(list(weights=object$weights,
category_weights=cat_weights,
group_weights=group_weights)
)
}