Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/sandbox/testing_DEoptim_cardinality_constraint.R
1433 views
1
2
# DEoptim with max positions constraint
3
# Uses fnMap to impose a cardinality constraint with DEoptim
4
5
library(PerformanceAnalytics)
6
library(PortfolioAnalytics)
7
library(DEoptim)
8
9
data(edhec)
10
R <- edhec
11
12
# use example objective function from
13
# http://cran.r-project.org/web/packages/DEoptim/vignettes/DEoptimPortfolioOptimization.pdf
14
obj <- function(w) {
15
if(sum(w) == 0){
16
w <- w + 1e-2
17
}
18
w <- w / sum(w)
19
CVaR <- ES(weights=w,
20
method="gaussian",
21
portfolio_method="component",
22
mu=mu,
23
sigma=sigma)
24
tmp1 <- CVaR$ES
25
tmp2 <- max(CVaR$pct_contrib_ES - 0.05, 0)
26
out <- tmp1 + tmp2
27
return(out)
28
}
29
30
mu <- colMeans(R)
31
sigma <- cov(R)
32
33
N <- ncol(R)
34
minw <- 0
35
maxw <- 1
36
lower <- rep(minw, N)
37
upper <- rep(maxw, N)
38
39
eps <- 0.025
40
41
weight_seq <- generatesequence(min=minw, max=maxw, by=0.001, rounding=3)
42
43
rpconstraint <- constraint(assets=N, min_sum=1-eps, max_sum=1+eps,
44
min=lower, max=upper, weight_seq=weight_seq)
45
set.seed(1234)
46
rp <- random_portfolios(rpconstraints=rpconstraint, permutations=N*10)
47
rp <- rp / rowSums(rp)
48
49
controlDE <- list(reltol=.000001,steptol=150, itermax = 5000,trace = 250,
50
NP=as.numeric(nrow(rp)),initialpop=rp)
51
set.seed(1234)
52
out1 <- DEoptim(fn = obj, lower=lower, upper=upper, control=controlDE)
53
54
weights1 <- out1$optim$bestmem
55
weights1 <- weights1 / sum(weights1)
56
sum(weights1)
57
out1$optim$bestval
58
59
# Implement a cardinality constraint for max positions with DEoptim
60
# http://grokbase.com/t/r/r-help/126fsz99gh/r-deoptim-example-illustrating-use-of-fnmap-parameter-for-enforcement-of-cardinality-constraints
61
mappingFun <- function(x, max.pos) {
62
N <- length(x)
63
num <- N - max.pos
64
# Two smallest weights are given a value of 0
65
x[order(x)][1:num] <- 0
66
x / sum(x)
67
}
68
69
out2 <- DEoptim(fn = obj, lower=lower, upper=upper, control=controlDE, fnMap=function(x) mappingFun(x, max.pos=10))
70
weights2 <- out2$optim$bestmem
71
weights2 <- weights2 / sum(weights2)
72
out2$optim$bestval
73
sum(round(weights2, 4))
74
75
# mappingGroupFun <- function(x) {
76
# i <- 1
77
# while(sum(x[1:2]) > 0.4 & i <= 5) {
78
# x[1:2] <- x[1:2] - 0.01
79
# i <- 1 + 1
80
# }
81
# x / sum(x)
82
# }
83
#
84
# out3 <- DEoptim(fn = obj, lower=lower, upper=upper, control=controlDE, fnMap=mappingGroupFun)
85
# weights3 <- out3$optim$bestmem
86
# sum(weights[1:2])
87
# out3$optim$bestval
88
# sum(round(weights3, 4))
89
90
91
92