Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/R/charts.ROI.R
1433 views
1
2
chart.Weight.ROI <- function(object, ..., neighbors = NULL, main="Weights", las = 3, xlab=NULL, cex.lab = 1, element.color = "darkgray", cex.axis=0.8, colorset=NULL, legend.loc="topright", cex.legend=0.8, plot.type="line"){
3
4
if(!inherits(object, "optimize.portfolio.ROI")) stop("object must be of class 'optimize.portfolio.ROI'")
5
6
if(plot.type %in% c("bar", "barplot")){
7
barplotWeights(object=object, ..., main=main, las=las, xlab=xlab, cex.lab=cex.lab, element.color=element.color, cex.axis=cex.axis, legend.loc=legend.loc, cex.legend=cex.legend, colorset=colorset)
8
} else if(plot.type == "line"){
9
10
columnnames = names(object$weights)
11
numassets = length(columnnames)
12
13
constraints <- get_constraints(object$portfolio)
14
15
if(is.null(xlab))
16
minmargin = 3
17
else
18
minmargin = 5
19
if(main=="") topmargin=1 else topmargin=4
20
if(las > 1) {# set the bottom border to accommodate labels
21
bottommargin = max(c(minmargin, (strwidth(columnnames,units="in"))/par("cin")[1])) * cex.lab
22
if(bottommargin > 10 ) {
23
bottommargin<-10
24
columnnames<-substr(columnnames,1,19)
25
# par(srt=45) #TODO figure out how to use text() and srt to rotate long labels
26
}
27
}
28
else {
29
bottommargin = minmargin
30
}
31
par(mar = c(bottommargin, 4, topmargin, 2) +.1)
32
if(any(is.infinite(constraints$max)) | any(is.infinite(constraints$min))){
33
# set ylim based on weights if box constraints contain Inf or -Inf
34
ylim <- range(object$weights)
35
} else {
36
# set ylim based on the range of box constraints min and max
37
ylim <- range(c(constraints$min, constraints$max))
38
}
39
plot(object$weights, type="b", col="blue", axes=FALSE, xlab='', ylim=ylim, ylab="Weights", main=main, pch=16, ...)
40
if(!any(is.infinite(constraints$min))){
41
points(constraints$min, type="b", col="darkgray", lty="solid", lwd=2, pch=24)
42
}
43
if(!any(is.infinite(constraints$max))){
44
points(constraints$max, type="b", col="darkgray", lty="solid", lwd=2, pch=25)
45
}
46
# if(!is.null(neighbors)){
47
# if(is.vector(neighbors)){
48
# xtract=extractStats(object)
49
# weightcols<-grep('w\\.',colnames(xtract)) #need \\. to get the dot
50
# if(length(neighbors)==1){
51
# # overplot nearby portfolios defined by 'out'
52
# orderx = order(xtract[,"out"])
53
# subsetx = head(xtract[orderx,], n=neighbors)
54
# for(i in 1:neighbors) points(subsetx[i,weightcols], type="b", col="lightblue")
55
# } else{
56
# # assume we have a vector of portfolio numbers
57
# subsetx = xtract[neighbors,weightcols]
58
# for(i in 1:length(neighbors)) points(subsetx[i,], type="b", col="lightblue")
59
# }
60
# }
61
# if(is.matrix(neighbors) | is.data.frame(neighbors)){
62
# # the user has likely passed in a matrix containing calculated values for risk.col and return.col
63
# nbweights<-grep('w\\.',colnames(neighbors)) #need \\. to get the dot
64
# for(i in 1:nrow(neighbors)) points(as.numeric(neighbors[i,nbweights]), type="b", col="lightblue")
65
# # note that here we need to get weight cols separately from the matrix, not from xtract
66
# # also note the need for as.numeric. points() doesn't like matrix inputs
67
# }
68
# }
69
# points(object$weights, type="b", col="blue", pch=16)
70
axis(2, cex.axis = cex.axis, col = element.color)
71
axis(1, labels=columnnames, at=1:numassets, las=las, cex.axis = cex.axis, col = element.color)
72
box(col = element.color)
73
}
74
}
75
76
#' @rdname chart.Weights
77
#' @method chart.Weights optimize.portfolio.ROI
78
#' @export
79
chart.Weights.optimize.portfolio.ROI <- chart.Weight.ROI
80
81
82
chart.Scatter.ROI <- function(object, ..., neighbors=NULL, return.col="mean", risk.col="ES", chart.assets=FALSE, element.color = "darkgray", cex.axis=0.8, xlim=NULL, ylim=NULL, rp=FALSE){
83
84
if(!inherits(object, "optimize.portfolio.ROI")) stop("object must be of class 'optimize.portfolio.ROI'")
85
86
R <- object$R
87
if(is.null(R)) stop("Returns object not detected, must run optimize.portfolio with trace=TRUE")
88
# If the user does not pass in rp, then we will generate random portfolios
89
if(rp){
90
permutations <- match.call(expand.dots=TRUE)$permutations
91
if(is.null(permutations)) permutations <- 2000
92
rp <- random_portfolios(portfolio=object$portfolio, permutations=permutations)
93
} else {
94
rp = NULL
95
}
96
97
# Get the optimal weights from the output of optimize.portfolio
98
wts <- object$weights
99
100
# cbind the optimal weights and random portfolio weights
101
rp <- rbind(wts, rp)
102
103
# Get the arguments from the optimize.portfolio$portfolio object
104
# to calculate the risk and return metrics for the scatter plot
105
tmp.args <- unlist(lapply(object$portfolio$objectives, function(x) x$arguments), recursive=FALSE)
106
tmp.args <- tmp.args[!duplicated(names(tmp.args))]
107
if(!is.null(tmp.args$portfolio_method)) tmp.args$portfolio_method <- "single"
108
arguments <- tmp.args
109
110
returnpoints <- applyFUN(R=R, weights=rp, FUN=return.col, arguments)
111
riskpoints <- applyFUN(R=R, weights=rp, FUN=risk.col, arguments)
112
113
if(chart.assets){
114
# Include risk reward scatter of asset returns
115
asset_ret <- scatterFUN(R=R, FUN=return.col, arguments)
116
asset_risk <- scatterFUN(R=R, FUN=risk.col, arguments)
117
} else {
118
asset_ret <- NULL
119
asset_risk <- NULL
120
}
121
122
# get limits for x and y axis
123
if(is.null(ylim)){
124
ylim <- range(c(returnpoints, asset_ret))
125
}
126
if(is.null(xlim)){
127
xlim <- range(c(riskpoints, asset_risk))
128
}
129
130
# Plot the portfolios
131
plot(x=riskpoints, y=returnpoints, xlab=risk.col, ylab=return.col, col="darkgray", xlim=xlim, ylim=ylim, axes=FALSE, ...)
132
# Plot the optimal portfolio
133
points(x=riskpoints[1], y=returnpoints[1], col="blue", pch=16) # optimal
134
text(x=riskpoints[1], y=returnpoints[1], labels="Optimal",col="blue", pos=4, cex=0.8)
135
136
# plot the risk-reward scatter of the assets
137
if(chart.assets){
138
points(x=asset_risk, y=asset_ret)
139
text(x=asset_risk, y=asset_ret, labels=colnames(R), pos=4, cex=0.8)
140
}
141
142
axis(1, cex.axis = cex.axis, col = element.color)
143
axis(2, cex.axis = cex.axis, col = element.color)
144
box(col = element.color)
145
}
146
147
#' @rdname chart.RiskReward
148
#' @method chart.RiskReward optimize.portfolio.ROI
149
#' @export
150
chart.RiskReward.optimize.portfolio.ROI <- chart.Scatter.ROI
151
152
153
charts.ROI <- function(ROI, rp=FALSE, risk.col="ES", return.col="mean", chart.assets=FALSE, cex.axis=0.8, element.color="darkgray", neighbors=NULL, main="ROI.Portfolios", xlim=NULL, ylim=NULL, ...){
154
# Specific to the output of the optimize_method=ROI
155
op <- par(no.readonly=TRUE)
156
layout(matrix(c(1,2)),heights=c(2,1.5),widths=1)
157
par(mar=c(4,4,4,2))
158
chart.Scatter.ROI(object=ROI, rp=rp, return.col=return.col, risk.col=risk.col, ..., chart.assets=chart.assets, element.color=element.color, cex.axis=cex.axis, main=main, xlim=xlim, ylim=ylim)
159
par(mar=c(2,4,0,2))
160
chart.Weight.ROI(object=ROI, neighbors=neighbors, ..., main="", las=3, xlab=NULL, cex.lab=1, element.color=element.color, cex.axis=cex.axis)
161
par(op)
162
}
163
164
#' @rdname plot
165
#' @method plot optimize.portfolio.ROI
166
#' @export
167
plot.optimize.portfolio.ROI <- function(x, ..., rp=FALSE, risk.col="ES", return.col="mean", chart.assets=FALSE, element.color="darkgray", neighbors=NULL, main="ROI.Portfolios", xlim=NULL, ylim=NULL){
168
charts.ROI(ROI=x, rp=rp, risk.col=risk.col, return.col=return.col, chart.assets=chart.assets, main=main, xlim=xlim, ylim=ylim, ...)
169
}
170
171
172
###############################################################################
173
# R (https://r-project.org/) Numeric Methods for Optimization of Portfolios
174
#
175
# Copyright (c) 2004-2021 Brian G. Peterson, Peter Carl, Ross Bennett, Kris Boudt
176
#
177
# This library is distributed under the terms of the GNU Public License (GPL)
178
# for full details see the file COPYING
179
#
180
# $Id$
181
#
182
###############################################################################
183
184