Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/R/charts.GenSA.R
1433 views
1
2
chart.Weight.GenSA <- 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.GenSA")) stop("object must be of class 'optimize.portfolio.GenSA'")
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(ROI)
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(ROI$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.GenSA
78
#' @export
79
chart.Weights.optimize.portfolio.GenSA <- chart.Weight.GenSA
80
81
chart.Scatter.GenSA <- function(object, ..., neighbors=NULL, return.col="mean", risk.col="ES", chart.assets=FALSE, element.color="darkgray", cex.axis=0.8, ylim=NULL, xlim=NULL, rp=FALSE){
82
83
if(!inherits(object, "optimize.portfolio.GenSA")) stop("object must be of class 'optimize.portfolio.GenSA'")
84
85
R <- object$R
86
if(is.null(R)) stop("Returns object not detected, must run optimize.portfolio with trace=TRUE")
87
# If the user does not pass in rp, then we will generate random portfolios
88
if(rp){
89
permutations <- match.call(expand.dots=TRUE)$permutations
90
if(is.null(permutations)) permutations <- 2000
91
rp <- random_portfolios(portfolio=object$portfolio, permutations=permutations)
92
} else {
93
rp = NULL
94
}
95
96
# Get the optimal weights from the output of optimize.portfolio
97
wts <- object$weights
98
99
# cbind the optimal weights and random portfolio weights
100
rp <- rbind(wts, rp)
101
102
# Get the arguments from the optimize.portfolio$portfolio object
103
# to calculate the risk and return metrics for the scatter plot
104
tmp.args <- unlist(lapply(object$portfolio$objectives, function(x) x$arguments), recursive=FALSE)
105
tmp.args <- tmp.args[!duplicated(names(tmp.args))]
106
if(!is.null(tmp.args$portfolio_method)) tmp.args$portfolio_method <- "single"
107
arguments <- tmp.args
108
109
returnpoints <- applyFUN(R=R, weights=rp, FUN=return.col, arguments)
110
riskpoints <- applyFUN(R=R, weights=rp, FUN=risk.col, arguments)
111
112
if(chart.assets){
113
# Include risk reward scatter of asset returns
114
asset_ret <- scatterFUN(R=R, FUN=return.col, arguments)
115
asset_risk <- scatterFUN(R=R, FUN=risk.col, arguments)
116
} else {
117
asset_ret <- NULL
118
asset_risk <- NULL
119
}
120
121
# get limits for x and y axis
122
if(is.null(ylim)){
123
ylim <- range(returnpoints, asset_ret)
124
}
125
if(is.null(xlim)){
126
xlim <- range(riskpoints, asset_risk)
127
}
128
129
# Plot the portfolios
130
plot(x=riskpoints, y=returnpoints, xlab=risk.col, ylab=return.col, col="darkgray", ylim=ylim, xlim=xlim, axes=FALSE, ...)
131
points(x=riskpoints[1], y=returnpoints[1], col="blue", pch=16) # optimal
132
text(x=riskpoints[1], y=returnpoints[1], labels="Optimal",col="blue", pos=4, cex=0.8)
133
134
# plot the risk-reward scatter of the assets
135
if(chart.assets){
136
points(x=asset_risk, y=asset_ret)
137
text(x=asset_risk, y=asset_ret, labels=colnames(R), pos=4, cex=0.8)
138
}
139
140
axis(1, cex.axis = cex.axis, col = element.color)
141
axis(2, cex.axis = cex.axis, col = element.color)
142
box(col = element.color)
143
}
144
145
#' @rdname chart.RiskReward
146
#' @method chart.RiskReward optimize.portfolio.GenSA
147
#' @export
148
chart.RiskReward.optimize.portfolio.GenSA <- chart.Scatter.GenSA
149
150
151
charts.GenSA <- function(GenSA, rp=FALSE, return.col="mean", risk.col="ES", chart.assets=FALSE, cex.axis=0.8, element.color="darkgray", neighbors=NULL, main="GenSA.Portfolios", xlim=NULL, ylim=NULL, ...){
152
# Specific to the output of the optimize_method=GenSA
153
op <- par(no.readonly=TRUE)
154
layout(matrix(c(1,2)),heights=c(2,2),widths=1)
155
par(mar=c(4,4,4,2))
156
chart.Scatter.GenSA(object=GenSA, 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, ...=...)
157
par(mar=c(2,4,0,2))
158
chart.Weight.GenSA(object=GenSA, neighbors=neighbors, las=3, xlab=NULL, cex.lab=1, element.color=element.color, cex.axis=cex.axis, ...=..., main="")
159
par(op)
160
}
161
162
163
#' @rdname plot
164
#' @method plot optimize.portfolio.GenSA
165
#' @export
166
plot.optimize.portfolio.GenSA <- function(x, ..., rp=FALSE, return.col="mean", risk.col="ES", chart.assets=FALSE, cex.axis=0.8, element.color="darkgray", neighbors=NULL, main="GenSA.Portfolios", xlim=NULL, ylim=NULL){
167
charts.GenSA(GenSA=x, rp=rp, return.col=return.col, risk.col=risk.col, chart.assets=chart.assets, cex.axis=cex.axis, element.color=element.color, neighbors=neighbors, main=main, xlim=xlim, ylim=ylim, ...=...)
168
}
169
170
171
###############################################################################
172
# R (https://r-project.org/) Numeric Methods for Optimization of Portfolios
173
#
174
# Copyright (c) 2004-2021 Brian G. Peterson, Peter Carl, Ross Bennett, Kris Boudt
175
#
176
# This library is distributed under the terms of the GNU Public License (GPL)
177
# for full details see the file COPYING
178
#
179
# $Id$
180
#
181
###############################################################################
182
183