-
Notifications
You must be signed in to change notification settings - Fork 0
/
CLA.R
229 lines (208 loc) · 8.11 KB
/
CLA.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
#### Started from "Version 8" (Ver8.R)
## Initialize the weight -- Find first free weight
initAlgo <- function(mu, lB, uB ) {
## New-ordered return, lB, uB with decreasing return
w <- c()
index.new <- order(mu,decreasing = TRUE) # new order with decreasing return
lB.new <- lB[index.new]
uB.new <- uB[index.new]
## free weight - starting solution
i.new <- 0
w.new <- lB.new # initially
while(sum(w.new) < 1) {
i.new <- i.new + 1
w.new[i.new] <- uB.new[i.new]
}
w.new[i.new] <- 1 - sum(w.new[-i.new])
w[index.new] <- w.new # back to original order
i <- index.new[i.new]
## return the index of first free asset and vector w :
list(index = i, weights = w)
}
## getMatrices -----------------------------------------------------------------
getMatrices <- function(mu, covar, w, f) {
## Slice covarF,covarFB,covarB,muF,muB,wF,wB
covarF <- covar[f,f]
muF <- mu[f]
b <- seq_along(mu)[-f]
covarFB <- covar[f,b]
wB <- w[b]
list(covarF = covarF, covarFB = covarFB, muF = muF, wB = wB)
}
computeInv <- function(get) {
solve(get$covarF, cbind(1, get$muF, get$covarFB %*% get$wB, deparse.level = 0L))
}
## computeW -----------------------------------------------------------------
computeW <- function(lam, inv, wB) {
## w2 <- inv[,1]; w3 <- inv[,2]; w1 <- inv[,3]
inv.s <- colSums(inv) # g1 <- inv.s[2]; g2 <- inv.s[1]; g4 <- inv.s[3]
## 1) compute gamma
g <- (-lam * inv.s[2] + (1- sum(wB) + inv.s[3]))/inv.s[1]
## 2) compute free weights
list(wF = - inv[,3] + g * inv[,1] + lam * inv[,2], gamma = g)
}
## computeLambda --------------------------------------------------------------
computeLambda <- function(wB, inv, i, bi.input) {
inv.s <- colSums(inv)
## c1 <- inv.s[1]; l2 <- inv.s[3]; c2i <- inv[i,2];
## c3 <- inv.s[2]; c4i <- inv[i, 1]; l1 <- sum(wB)
c1 <- inv.s[1]
if(length(bi.input) == 1L) { # 1.bound to free
c4i <- inv[i, 1]
Ci <- - c1 * inv[i, 2] + inv.s[2] * c4i
## return lambda :
if(Ci == 0)
0
else
((1- sum(wB) + inv.s[3])* c4i- c1 * (bi.input + inv[i, 3]))/Ci
}
else { # 2.free to bound
c4i <- inv[, 1]
Ci <- - c1 * inv[, 2] + inv.s[2] * c4i
bi <- bi.input[i, 1] # bi.lB
bi[Ci > 0] <- bi.input[i[Ci > 0], 2] # bi.uB
bi[Ci == 0] <- 0
## return lambda and boundary :
list(lambda = ((1- sum(wB) + inv.s[3]) * c4i- c1 *(bi + inv[, 3]))/Ci,
bi = bi)
}
}
MS <- function(weights_set, mu, covar) {
Sig2 <- colSums(weights_set *(covar %*% weights_set) )
cbind(Sig = sqrt(Sig2), Mu = as.vector(t(weights_set) %*% mu))
}
CLA <- function(mu, covar, lB, uB, tol.lambda = 1e-7,
give.MS = TRUE, keep.names = TRUE) {
## minimal argument checks
cl <- match.call()
n <- length(mu)
if(length(lB) == 1) lB <- rep.int(lB, n)
if(length(uB) == 1) uB <- rep.int(uB, n)
stopifnot(is.numeric(mu), is.matrix(covar), identical(dim(covar), c(n,n)),
is.numeric(lB), length(lB) == n,
is.numeric(uB), length(uB) == n, lB <= uB)# and in [0,1]
## Compute the turning points, free sets and weights
ans <- initAlgo(mu, lB, uB)
f <- ans$index
w <- ans$weights
weights_set <- w # store solution
lambdas <- NA # The first step has no lambda or gamma, add NA instead.
gammas <- NA
free_indices <- list(f)
lam <- 1 # set non-zero lam
while ( lam > 0 && length(f) < length(mu)) {
## 1) case a): Bound one free weight F -> B
l_in <- 0
if(length(f) > 1 ) {
compl <- computeLambda(wB = w[-f], inv = inv, # inv from last step k (k > 1)
i = f, bi.input = cbind(lB, uB))
lam_in <- compl$lambda
bi <- compl$bi
k <- which.max(lam_in)
i_in <- f[k]
bi_in <- bi[k]
l_in <- lam_in[k]
}
## 2) case b): Free one bounded weight B -> F
b <- seq_along(mu)[-f]
inv_list <- lapply(b, function(bi) {
get_i <- getMatrices(mu, covar, w, c(f,bi))
computeInv(get_i)
})
fi <- length(f) + 1
lam_out <- sapply(seq_along(b), function(i) {
computeLambda(wB = w[b[-i]], inv = inv_list[[i]],
i = fi, bi.input = w[b[i]])
})
if (length(lambdas) > 1 && any(!(sml <- lam_out < lam*(1-tol.lambda)))) {
lam_out <- lam_out[sml]
b <- b [sml]
inv_list <- inv_list[sml]
}
k <- which.max(lam_out)
i_out <- b [k] # one only !
l_out <- lam_out[k]
inv_out <- inv_list[[k]]
## 3) decide lambda
lam <- max(l_in, l_out, 0)
if(lam > 0) { # remove i_in from f; or add i_out into f
if(l_in > l_out ) {
w[i_in] <- bi_in # set value at the correct boundary
f <- f[f != i_in]
getM <- getMatrices(mu, covar, w, f)
inv <- computeInv(getM)
}
else {
f <- c(f,i_out)
inv <- inv_out
}
compW <- computeW(lam, inv = inv, wB = w[-f])
}
else{ # 4) if max(l_in, l_out) < 0, "stop" when at the min var solution!
compW <- computeW(lam = lam, inv = inv, wB = w[-f])
## muF = 0 not necessary, get1 replaced by getM (ie getM from previous step)
}
wF <- compW$wF
g <- compW$gamma
w[f] <- wF[seq_along(f)]
lambdas <- c(lambdas, lam)
weights_set <- cbind(weights_set, w, deparse.level = 0L) # store solution
gammas <- c(gammas, g)
free_indices <- c(free_indices, list(sort(f)))
}# end While
if(keep.names) rownames(weights_set) <- names(mu)
#### FIXME: This change also needs changes in the ../tests/SP500-ex.R !
structure(class = "CLA",
list(weights_set = weights_set,
free_indices = free_indices,
gammas = gammas, lambdas = lambdas,
MS_weights = if(give.MS)
MS(weights_set = weights_set, mu = mu, covar = covar),
call = cl))
}
## print method
print.CLA <- function(x, ...) {
cat("Call: ", paste(deparse(x$call), sep = "\n", collapse = "\n"),
"\n", sep = "")
wts <- x$weights_set
n <- nrow(wts)
nT <- ncol(wts)
cat(gettextf("Critical Line Algorithm for n = %d assets, ", n),
gettextf("resulting in %d turning points", nT),"\n", sep="")
## For now; we can do better later:
cat("Overview of result parts:\n")
utils::str(x[1:5], max.level = 1, give.attr=FALSE)
## TODO better, e.g., summarizing the number "active assets"
## and those with non-0 weights -- only if lower bounds were (mostly) 0
invisible(x)
}
### TODO: plot method -- efficient frontier
## As basically from .../YanhaoShi/R/Functions/Plot.R :
MS_plot <- function(ms, type = "o",
main = "Efficient Frontier",
xlab = expression(sigma(w)),
ylab = expression(mu(w)),
col = adjustcolor("blue", alpha.f = 0.5),
pch = 16, ...) {
## list of weights_set, legend...
stopifnot(is.matrix(ms), ncol(ms) == 2)
plot(ms[,"Sig"], ms[,"Mu"], type=type, pch=pch, col=col,
xlab = xlab, ylab=ylab, main=main, ...)
}
## FIXME: --> see also in ../man/plot.CLA.Rd
## -----
## 0) Use findMu() and findSig() to draw the lines *between*
## 1) Learn from Tobias Setz to plot the lower part of the feasible region
## 2) Better title, using 'call'
## 3) mark some critical points particularly
## 4) give information about the *number* critical points / weights sets
## 5) consider using a 'add = FALSE' argument and then use 'lines()'
plot.CLA <- function(x, type = "o", main = "Efficient Frontier",
xlab = expression(sigma(w)),
ylab = expression(mu(w)),
col = adjustcolor("blue", alpha.f = 0.5),
pch = 16, ...) {
stopifnot(is.matrix(ms <- x$MS_weights))
plot(ms[,"Sig"], ms[,"Mu"], type=type, pch=pch, col=col,
xlab=xlab, ylab=ylab, main=main, ...)
}