Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/sandbox/Risk_budget_functions.R
1433 views
1
2
PortfolioOptim = function( minriskcriterion = "mES" , MinMaxComp = F, percriskcontribcriterion = "mES" ,
3
R = NULL, mu = NULL , sigma = NULL, M3=NULL,M4=NULL, alpha = 0.05, alphariskbudget = 0.05,
4
lower = NULL , upper = NULL, Riskupper = NULL, Returnlower = NULL, RBlower = NULL , RBupper = NULL, precision = 1e-3 ,
5
controlDE = list( VTR = 0 , NP=200, trace = FALSE ) , heuristic=TRUE ){
6
7
# Description:
8
# This function produces the portfolio that minimimizes
9
# either the portfolio risk (when MinMaxComp = F) or the portfolio concentration (when MinMaxComp = T)
10
# subject to
11
# lower <= weights <= upper
12
# risk <= Riskupper
13
# expected return >= Returnlower
14
# RBlower <= percentage risk <= RBupper
15
16
# Input:
17
# Either the multivariate return series is given or estimates of the mean, covariance, coskewness or cokurtosis
18
require(zoo); require(PerformanceAnalytics); require(DEoptim)
19
20
if( !is.null(R) ){
21
R = clean.boudt2( R , alpha = alphariskbudget )[[1]];
22
T = nrow(R);N=ncol(R)
23
mu = matrix( as.vector(apply(R,2,'mean')),ncol=1);
24
sigma = cov(R);
25
M3 = PerformanceAnalytics:::M3.MM(R)
26
M4 = PerformanceAnalytics:::M4.MM(R)
27
}else{ N = length(mu) }
28
29
if( is.null(lower) ){ lower = rep(0,N) } ; if( is.null(upper) ){ upper = rep(1,N) }
30
if( is.null(RBlower) ){ RBlower = rep(-Inf,N) } ; if( is.null(RBupper) ){ RBupper = rep(Inf,N) }
31
if( is.null(Riskupper) ){ Riskupper = Inf } ; if( is.null(Returnlower) ){ Returnlower = -Inf }
32
33
switch( percriskcontribcriterion ,
34
StdDev = { percriskcontrib = function(w){ return( Portsd(w,mu=mu,sigma=sigma) ) }},
35
GVaR = { percriskcontrib = function(w){ return( PortgausVaR(w,alpha=alphariskbudget,mu=mu,sigma=sigma) ) }},
36
GES = { percriskcontrib = function(w){ return( PortgausES(w,mu=mu,alpha=alphariskbudget,sigma=sigma) ) }},
37
mVaR = { percriskcontrib = function(w){ return( PortMVaR(w,mu=mu,alpha=alphariskbudget,sigma=sigma,M3=M3,M4=M4) ) }},
38
mES = { percriskcontrib = function(w){ return( operPortMES(w,mu=mu,alpha=alphariskbudget,sigma=sigma,M3=M3,M4=M4) ) }}
39
) #end function that finds out which percentage risk contribution criterion to use
40
switch( minriskcriterion ,
41
StdDev = { prisk = function(w){ return( stddevfun(w,mu=mu,sigma=sigma) ) }},
42
GVaR = { prisk = function(w){ return( gausVaRfun(w,alpha=alpha,mu=mu,sigma=sigma) ) }},
43
GES = { prisk = function(w){ return( gausESfun(w,mu=mu,alpha=alpha,sigma=sigma) ) }},
44
mVaR = { prisk = function(w){ return( MVaRfun(w,mu=mu,alpha=alpha,sigma=sigma,M3=M3,M4=M4) )}},
45
mES = { prisk = function(w){ return( operMESfun(w,mu=mu,alpha=alpha,sigma=sigma,M3=M3,M4=M4)) }}
46
) #end function that finds out which risk function to minimize
47
48
abspenalty = 1e6; relpenalty = 100*N;
49
if( heuristic ){
50
objective = function( w ){
51
w = w/sum(w)
52
cont = percriskcontrib( w ); percrisk = cont[[3]]; crisk = cont[[2]] ;
53
if(MinMaxComp){ out = max( crisk ) }else{ out = prisk(w) }
54
# add weight constraints
55
out_con = out + out*abspenalty*sum( 1*( w < lower )+1*( w > upper ) )
56
# add risk budget constraint
57
con1 = sum( (percrisk-RBupper)*( percrisk > RBupper ),na.rm=TRUE ) ; if( is.na(con1) ){ con1 = 0 } # because of Inf*0
58
con2 = sum( (RBlower-percrisk)*( percrisk < RBlower ),na.rm=TRUE ); if( is.na(con2) ){ con2 = 0 }
59
out_con = out_con + out*relpenalty*(con1+con2)
60
# add minimum risk constraint
61
con = ( prisk(w) - Riskupper)*( prisk(w) > Riskupper ); if( is.na(con) ){ con = 0 }
62
out_con = out_con + out*relpenalty*con
63
# add minimum return constraint
64
# portfolio return and risk are in the same unit, but portfolio return is typically some orders of magnitude smaller
65
# say: as a very conservative choice: 100
66
preturn = sum( w*mu ) ;
67
con = ( Returnlower - preturn)*( preturn < Returnlower ); if( is.na(con) ){ con = 0 }
68
out_con = out_con + out*100*relpenalty*con
69
return(out_con)
70
}
71
minw = DEoptim( fn = objective , lower = lower , upper = upper , control = controlDE)
72
fvalues = minw$member$bestval
73
diff = as.vector( quantile(fvalues,0.10) - min(fvalues) )
74
print(c("diff",diff))
75
best = min( fvalues ) ; print(best)
76
bestsol = minw ;
77
78
while( diff>1e-6 ){
79
pop = as.matrix(minw$member$pop)
80
pop[1,] = minw$optim$bestmem;
81
minw = DEoptim( fn = objective , lower = lower , upper = upper ,
82
control = list( itermax = 150, NP=as.numeric(nrow(pop)) , initialpop=pop,trace=F ) )
83
fvalues = minw$member$bestval
84
diff = best - min(fvalues) ;
85
if( diff > 0 ){ best = min( fvalues ) ; bestsol = minw ; print(best) }
86
}
87
minw = bestsol$optim$bestmem/sum(bestsol$optim$bestmem) ; #full investment constraint
88
}else{
89
objective = function( w ){
90
if(sum(w)==0){w=w+0.001}
91
w = w/sum(w)
92
cont = percriskcontrib( w ); percrisk = cont[[3]]; crisk = cont[[2]] ;
93
if(MinMaxComp){ out = max( crisk ) }else{ out = prisk(w) }
94
# add risk budget constraint
95
con1 = sum( (percrisk-RBupper)*( percrisk > RBupper ),na.rm=TRUE ) ; if( is.na(con1) ){ con1 = 0 } # because of Inf*0
96
con2 = sum( (RBlower-percrisk)*( percrisk < RBlower ),na.rm=TRUE ); if( is.na(con2) ){ con2 = 0 }
97
out_con = out + out*relpenalty*(con1+con2)
98
# add minimum risk constraint
99
con = ( prisk(w) - Riskupper)*( prisk(w) > Riskupper ); if( is.na(con) ){ con = 0 }
100
out_con = out_con + out*relpenalty*con
101
return(out_con)
102
}
103
104
if(Returnlower==-Inf){
105
inittheta = rep(1,N)/N
106
out = optim( par=inittheta, f = objective, lower = lower, upper = upper )
107
}else{
108
Amat = rbind(diag(x =1,nrow=N,ncol=N), diag(x =-1,nrow=N,ncol=N), rep(1,N), rep(-1,N),as.vector(mu))
109
inittheta = rep(0.001,N);
110
inittheta[mu==max(mu)] = 1; inittheta = 1-sum(inittheta[mu!=max(mu)] );
111
out = constrOptim( theta=inittheta, f = objective, grad=NULL,ui=Amat,
112
ci = c(rep(0,N),rep(-1,N),0.99999,-1.0001,Returnlower) )
113
}
114
115
minw = out$par/sum(out$par)
116
}
117
cont = percriskcontrib( minw ); percrisk = cont[[3]]; crisk = cont[[2]] ;
118
# check
119
print( "out = list( minw , sum( minw*mu ) , prisk(minw) , percriskcontrib(minw)" )
120
out = list( minw , sum( minw*mu ) , prisk(minw) , percrisk , crisk )
121
print( out )
122
return(out)
123
}
124
125
findportfolio.dynamic = function(R, from, to, names.input = NA, names.assets,
126
p = 0.95 , priskbudget = 0.95, mincriterion = "mES" , percriskcontribcriterion = "mES" ,
127
strategy , controlDE = list( VTR = 0 , NP=200 ) )
128
{ # @author Kris Boudt and Brian G. Peterson
129
130
# Description:
131
#
132
# Performs a loop over the reallocation periods with estimation samples given by from:to
133
# It calls the function RBconportfolio to obtain the optimal weights of the strategy.
134
#
135
# @todo
136
#
137
# R matrix/zoo holding historical returns on risky assets
138
#
139
# names vector holding the names of the .csv files to be read
140
#
141
# from, to define the estimation sample
142
#
143
# criteria the criterion to be optimized
144
#
145
# columns.crit the columns of R in which the criteria are located
146
#
147
# percriskcontribcriterion risk measure used for the risk budget constraints
148
#
149
# strategy = c( "EqualRisk" , "EqualWeight" , "MinRisk" , "MinRiskConc" ,
150
# "MinRisk_PositionLimit" , "MinRisk_RiskLimit" , "MinRisk_ReturnTarget",
151
# "MinRiskConc_PositionLimit" , "MinRiskConc_RiskLimit" , "MinRiskConc_ReturnTarget")
152
153
# Return:
154
# List with first element optimal weights per reallocation period and associated percentage CVaR contributions.
155
156
# Create a matrix that will hold for each method and each vector the best weights
157
158
cPeriods = length(from);
159
160
out = matrix( rep(0, cPeriods*(cAssets)) , ncol= (cAssets) );
161
RCout = matrix( rep(0, cPeriods*(cAssets)) , ncol= (cAssets) );
162
# first cPeriods rows correspond to cCriteria[1] and so on
163
164
# downside risk
165
alpha = 1 - p;
166
alphariskbudget = 1-priskbudget;
167
168
# Estimation of the return mean vector, covariance, coskewness and cokurtosis matrix
169
170
171
if(strategy=="EqualRisk"){
172
lower = rep(0,cAssets); upper=rep(1,cAssets)
173
RBlower = rep(1/cAssets,cAssets) ; RBupper = rep(1/cAssets,cAssets) ;
174
}
175
176
if(strategy=="EqualWeight"){
177
lower = rep(1/cAssets,cAssets); upper=rep(1/cAssets,cAssets)
178
RBlower = rep(-Inf,cAssets) ; RBupper = rep(Inf,cAssets) ;
179
}
180
181
if(strategy=="MinRisk" | strategy=="MinRiskConc" | strategy=="MinRisk_ReturnTarget" | strategy=="MinRiskConc_ReturnTarget"){
182
lower = rep(0,cAssets); upper=rep(1,cAssets)
183
RBlower = rep(-Inf,cAssets) ; RBupper = rep(Inf,cAssets) ;
184
}
185
186
MinMaxComp = F; mutarget = -Inf;
187
if( strategy=="MinRiskConc" | strategy=="MinRiskConc_PositionLimit" | strategy=="MinRiskConc_RiskLimit" | strategy=="MinRiskConc_ReturnTarget" ){
188
MinMaxComp = T;
189
}
190
191
if(strategy=="MinRisk_PositionLimit" | strategy=="MinRiskConc_PositionLimit"){
192
lower = rep(0,cAssets); upper=rep(0.4,cAssets)
193
RBlower = rep(-Inf,cAssets) ; RBupper = rep(Inf,cAssets) ;
194
}
195
196
if(strategy=="MinRisk_RiskLimit" | strategy=="MinRiskConc_RiskLimit"){
197
lower = rep(0,cAssets); upper=rep(1,cAssets)
198
RBlower = rep(-Inf,cAssets) ; RBupper = rep(0.40,cAssets) ;
199
}
200
201
for( per in c(1:cPeriods) ){
202
203
print("-----------New estimation period ends on observation------------------")
204
print( paste(to[per],"out of total number of obs equal to", max(to) ));
205
print("----------------------------------------------------------------")
206
207
# Estimate GARCH model with data from inception
208
209
inception.R = window(R, start = as.Date(from[1]) , end = as.Date(to[per]) );
210
211
# Estimate comoments of innovations with rolling estimation windows
212
in.sample.R = window(R, start = as.Date(from[per]) , end = as.Date(to[per]) );
213
in.sample.R = checkData(in.sample.R, method="matrix");
214
215
# Estimation of mean return
216
M = c();
217
library(TTR)
218
Tmean = 47 # monthly returns: 4 year exponentially weighted moving average
219
for( i in 1:cAssets ){
220
M = cbind( M , as.vector( EMA(x=inception.R[,i],n=Tmean) ) ) #2/(n+1)
221
}
222
M = zoo( M , order.by=time(inception.R) )
223
224
# Center returns (shift by one observations since M[t,] is rolling mean t-Tmean+1,...,t; otherwise lookahead bias)
225
inception.R.cent = inception.R;
226
ZZ = matrix( rep(as.vector( apply( inception.R[1:Tmean, ] , 2 , 'mean' )),Tmean),byrow=T,nrow=Tmean);
227
inception.R.cent[1:Tmean,] = inception.R[1:Tmean, ] - ZZ;
228
if( nrow(inception.R)>(Tmean+1) ){
229
A = M[Tmean:(nrow(inception.R)-1),];
230
A = zoo( A , order.by = time(inception.R[(Tmean+1):nrow(inception.R), ])) ; #shift dates; otherwise zoo poses problem
231
inception.R.cent[(Tmean+1):nrow(inception.R), ] = inception.R[(Tmean+1):nrow(inception.R), ] - A}
232
233
# Garch estimation
234
S = c();
235
for( i in 1:cAssets ){
236
gout = garchFit(formula ~ garch(1,1), data = inception.R.cent[,i],include.mean = F, cond.dist="QMLE", trace = FALSE )
237
if( as.vector(gout@fit$coef["alpha1"]) < 0.01 ){
238
sigmat = rep( sd( as.vector(inception.R.cent[,i])), length(inception.R.cent[,i]) );
239
}else{
240
sigmat = gout@sigma.t
241
}
242
S = cbind( S , sigmat)
243
}
244
S = zoo( S , order.by=time(inception.R.cent) )
245
246
# Estimate correlation, coskewness and cokurtosis matrix locally using cleaned innovation series in three year estimation window
247
selectU = window(inception.R.cent, start = as.Date(from[per]) , end = as.Date(to[per]) )
248
selectU = selectU/window(S, start = as.Date(from[per]) , end = as.Date(to[per]) );
249
selectU = clean.boudt2(selectU , alpha = 0.05 )[[1]];
250
Rcor = cor(selectU)
251
D = diag( as.vector(tail(S,n=1) ),ncol=cAssets )
252
sigma = D%*%Rcor%*%D
253
254
# we only need mean and conditional covariance matrix of last observation
255
mu = matrix(tail(M,n=1),ncol=1 ) ;
256
D = diag( as.vector(as.vector(tail(S,n=1) ) ),ncol=cAssets )
257
sigma = D%*%Rcor%*%D
258
in.sample.T = nrow(selectU);
259
# set volatility of all U to last observation, such that cov(rescaled U)=sigma
260
selectU = selectU*matrix( rep(as.vector(tail(S,n=1)),in.sample.T ) , ncol = cAssets , byrow = T )
261
M3 = PerformanceAnalytics:::M3.MM(selectU)
262
M4 = PerformanceAnalytics:::M4.MM(selectU)
263
264
265
mESfun = function(series){ return( operMES(series,alpha=alpha,2) ) }
266
267
268
if(strategy=="MinRisk_ReturnTarget" | strategy=="MinRiskConc_ReturnTarget"){
269
mutarget = mean( mu );
270
print( c("Minimum return requirement is" , mutarget) )
271
}
272
273
if(strategy=="EqualWeight"){
274
sol1 = rep(1/cAssets,cAssets);
275
switch( percriskcontribcriterion ,
276
StdDev = { percriskcontrib = function(w){ cont = Portsd(w,mu=mu,sigma=sigma)[[3]] ; return( cont ) }},
277
GVaR = {percriskcontrib = function(w){ cont = PortgausVaR(w,alpha=alphariskbudget,mu=mu,sigma=sigma)[[3]] ; return( cont ) }},
278
GES = {percriskcontrib = function(w){ cont = PortgausES(w,mu=mu,alpha=alphariskbudget,sigma=sigma)[[3]] ; return( cont ) }},
279
mVaR = {percriskcontrib = function(w){ cont = PortMVaR(w,mu=mu,alpha=alphariskbudget,sigma=sigma,M3=M3,M4=M4)[[3]] ; return( cont ) }},
280
mES = {percriskcontrib = function(w){ cont = operPortMES(w,mu=mu,alpha=alphariskbudget,sigma=sigma,M3=M3,M4=M4)[[3]] ; return( cont ) }
281
}
282
)
283
sol2 = percriskcontrib( sol1 )
284
solution = list( sol1 , sol2 ) ;
285
}else{
286
solution = PortfolioOptim( minriskcriterion = "mES" , MinMaxComp = MinMaxComp, percriskcontribcriterion = "mES" ,
287
mu = mu , sigma = sigma, M3=M3 , M4=M4 , alpha = alpha , alphariskbudget = alphariskbudget ,
288
lower = lower , upper = upper , Riskupper = Inf , Returnlower= mutarget , RBlower = RBlower, RBupper = RBupper ,
289
controlDE = controlDE )
290
solution = list( solution[[1]] , solution[[4]] );
291
}
292
out[ per, ] = as.vector( solution[[1]] )
293
RCout[per, ] = as.vector( solution[[2]] )
294
295
}#end loop over the rebalancing periods; indexed by per=1,...,cPeriods
296
297
298
# Output save
299
rownames(out) = rownames(RCout) = names.input; colnames(out) = colnames(RCout) = names.assets;
300
301
EWweights = c( rep(1/cAssets,cAssets) )
302
EWweights = matrix ( rep(EWweights,cPeriods) , ncol=(cAssets) , byrow = TRUE )
303
rownames(EWweights) = names.input; colnames(EWweights) = names.assets;
304
305
return( list( out, RCout) )
306
}
307
308
clean.boudt2 =
309
function (R, alpha = 0.01, trim = 0.001)
310
{
311
# @author Kris Boudt and Brian Peterson
312
# Cleaning method as described in
313
# Boudt, Peterson and Croux. 2009. Estimation and decomposition of downside risk for portfolios with non-normal returns. Journal of Risk.
314
315
stopifnot("package:robustbase" %in% search() || require("robustbase",
316
quietly = TRUE))
317
R = checkData(R, method = "zoo")
318
T = dim(R)[1]
319
date = c(1:T)
320
N = dim(R)[2]
321
MCD = covMcd(as.matrix(R), alpha = 1 - alpha)
322
# mu = as.matrix(MCD$raw.center)
323
mu = MCD$raw.center
324
sigma = MCD$raw.cov
325
invSigma = solve(sigma)
326
vd2t = c()
327
cleaneddata = R
328
outlierdate = c()
329
for (t in c(1:T)) {
330
d2t = as.matrix(R[t, ] - mu) %*% invSigma %*% t(as.matrix(R[t,] - mu))
331
vd2t = c(vd2t, d2t)
332
}
333
out = sort(vd2t, index.return = TRUE)
334
sortvd2t = out$x
335
sortt = out$ix
336
empirical.threshold = sortvd2t[floor((1 - alpha) * T)]
337
T.alpha = floor(T * (1 - alpha)) + 1
338
cleanedt = sortt[c(T.alpha:T)]
339
for (t in cleanedt) {
340
if (vd2t[t] > qchisq(1 - trim, N)) {
341
cleaneddata[t, ] = sqrt(max(empirical.threshold,
342
qchisq(1 - trim, N))/vd2t[t]) * R[t, ]
343
outlierdate = c(outlierdate, date[t])
344
}
345
}
346
return(list(cleaneddata, outlierdate))
347
}
348
349
350
Ipower = function(power,h)
351
{
352
353
fullprod = 1;
354
355
if( (power%%2)==0 ) #even number: number mod is zero
356
{
357
pstar = power/2;
358
for(j in c(1:pstar))
359
{
360
fullprod = fullprod*(2*j)
361
}
362
I = fullprod*dnorm(h);
363
364
for(i in c(1:pstar) )
365
{
366
prod = 1;
367
for(j in c(1:i) )
368
{
369
prod = prod*(2*j)
370
}
371
I = I + (fullprod/prod)*(h^(2*i))*dnorm(h)
372
}
373
}
374
else{
375
pstar = (power-1)/2
376
for(j in c(0:pstar) )
377
{
378
fullprod = fullprod*( (2*j)+1 )
379
}
380
I = -fullprod*pnorm(h);
381
382
for(i in c(0:pstar) )
383
{
384
prod = 1;
385
for(j in c(0:i) )
386
{
387
prod = prod*( (2*j) + 1 )
388
}
389
I = I + (fullprod/prod)*(h^( (2*i) + 1))*dnorm(h)
390
}
391
}
392
return(I)
393
}
394
395
396
# Definition of statistics needed to compute Gaussian and modified VaR and ES for the return series of portfolios
397
# and to compute the contributions to portfolio downside risk, made by the different positions in the portfolio.
398
#----------------------------------------------------------------------------------------------------------------
399
400
401
402
m2 = function(w,sigma)
403
{
404
return(t(w)%*%sigma%*%w)
405
}
406
derm2 = function(w,sigma)
407
{
408
return(2*sigma%*%w)
409
}
410
m3 = function(w,M3)
411
{
412
return(t(w)%*%M3%*%(w%x%w))
413
}
414
derm3 = function(w,M3)
415
{
416
return(3*M3%*%(w%x%w))
417
}
418
m4 = function(w,M4)
419
{
420
return(t(w)%*%M4%*%(w%x%w%x%w))
421
}
422
derm4 = function(w,M4)
423
{
424
return(4*M4%*%(w%x%w%x%w))
425
}
426
427
StdDevfun = function(w,sigma){ return( sqrt( t(w)%*%sigma%*%w )) }
428
429
GVaRfun = function(w,alpha,mu,sigma){ return (- (t(w)%*%mu) - qnorm(alpha)*sqrt( t(w)%*%sigma%*%w ) ) }
430
431
mVaRfun = function(w,alpha,mu,sigma,M3,M4){
432
pm4 = t(w)%*%M4%*%(w%x%w%x%w) ; pm3 = t(w)%*%M3%*%(w%x%w) ; pm2 = t(w)%*%sigma%*%w ;
433
skew = pm3 / pm2^(3/2);
434
exkurt = pm4 / pm2^(2) - 3; z = qnorm(alpha);
435
h = z + (1/6)*(z^2 -1)*skew
436
h = h + (1/24)*(z^3 - 3*z)*exkurt - (1/36)*(2*z^3 - 5*z)*skew^2;
437
return (- (t(w)%*%mu) - h*sqrt( pm2 ) ) }
438
439
resmVaRfun = function(w,alpha,mu,sigma,ressigma,M3,M4){
440
pm4 = t(w)%*%M4%*%(w%x%w%x%w) ; pm3 = t(w)%*%M3%*%(w%x%w) ; pm2 = t(w)%*%sigma%*%w ; respm2 = t(w)%*%resSigma%*%w ;
441
skew = pm3 / respm2^(3/2);
442
exkurt = pm4 / respm2^(2) - 3; z = qnorm(alpha);
443
h = z + (1/6)*(z^2 -1)*skew
444
h = h + (1/24)*(z^3 - 3*z)*exkurt - (1/36)*(2*z^3 - 5*z)*skew^2;
445
return (- (t(w)%*%mu) - h*sqrt( pm2 ) ) }
446
447
GESfun = function(w,alpha,mu,sigma,M3,M4){
448
return (- (t(w)%*%mu) + dnorm(qnorm(alpha))*sqrt(t(w)%*%sigma%*%w)/alpha ) }
449
450
operMESfun = function(w,alpha,mu,sigma,M3,M4){
451
pm4 = t(w)%*%M4%*%(w%x%w%x%w) ; pm3 = t(w)%*%M3%*%(w%x%w) ; pm2 = t(w)%*%sigma%*%w ;
452
skew = pm3 / pm2^(3/2);
453
exkurt = pm4 / pm2^(2) - 3; z = qnorm(alpha);
454
h = z + (1/6)*(z^2 -1)*skew
455
h = h + (1/24)*(z^3 - 3*z)*exkurt - (1/36)*(2*z^3 - 5*z)*skew^2;
456
E = dnorm(h)
457
E = E + (1/24)*( Ipower(4,h) - 6*Ipower(2,h) + 3*dnorm(h) )*exkurt
458
E = E + (1/6)*( Ipower(3,h) - 3*Ipower(1,h) )*skew;
459
E = E + (1/72)*( Ipower(6,h) -15*Ipower(4,h)+ 45*Ipower(2,h) - 15*dnorm(h) )*(skew^2)
460
E = E/alpha
461
return (- (t(w)%*%mu) - sqrt(pm2)*min(-E,h) ) }
462
463
precision = 4;
464
465
Portmean = function(w,mu,precision=4)
466
{
467
return( list( round( t(w)%*%mu , precision) , round ( as.vector(w)*as.vector(mu) , precision ) , round( as.vector(w)*as.vector(mu)/t(w)%*%mu) , precision) )
468
}
469
470
Portsd = function(w,sigma,precision=4)
471
{
472
pm2 = m2(w,sigma)
473
dpm2 = derm2(w,sigma)
474
dersd = (0.5*as.vector(dpm2))/sqrt(pm2);
475
contrib = dersd*as.vector(w)
476
return(list( round( sqrt(pm2) , precision ) , round( contrib , precision ) , round ( contrib/sqrt(pm2) , precision) ))
477
}
478
479
480
PortgausVaR = function(alpha,w,mu,sigma,precision=4){
481
location = t(w)%*%mu
482
pm2 = m2(w,sigma)
483
dpm2 = derm2(w,sigma)
484
VaR = - location - qnorm(alpha)*sqrt(pm2)
485
derVaR = - as.vector(mu)- qnorm(alpha)*(0.5*as.vector(dpm2))/sqrt(pm2);
486
contrib = derVaR*as.vector(w)
487
return(list( round( VaR , precision ) , round ( contrib , precision ) , round( contrib/VaR , precision) ))
488
}
489
490
PortgausES = function(alpha,w,mu,sigma,precision=4){
491
location = t(w)%*%mu
492
pm2 = m2(w,sigma)
493
dpm2 = derm2(w,sigma)
494
ES = - location + dnorm(qnorm(alpha))*sqrt(pm2)/alpha
495
derES = - as.vector(mu) + (1/alpha)*dnorm(qnorm(alpha))*(0.5*as.vector(dpm2))/sqrt(pm2);
496
contrib = as.vector(w)*derES;
497
return(list( round( ES , precision ) , round( contrib , precision) , round( contrib/ES , precision) ))
498
}
499
500
PortSkew = function(w,sigma,M3)
501
{
502
pm2 = m2(w,sigma)
503
pm3 = m3(w,M3)
504
skew = pm3 / pm2^(3/2);
505
return( skew )
506
}
507
508
PortKurt = function(w,sigma,M4)
509
{
510
pm2 = m2(w,sigma)
511
pm4 = m4(w,M4)
512
kurt = pm4 / pm2^(2) ;
513
return( kurt )
514
}
515
516
PortMVaR = function(alpha,w,mu,sigma,M3,M4,precision=4)
517
{
518
z = qnorm(alpha)
519
location = t(w)%*%mu
520
pm2 = m2(w,sigma)
521
dpm2 = as.vector( derm2(w,sigma) )
522
pm3 = m3(w,M3)
523
dpm3 = as.vector( derm3(w,M3) )
524
pm4 = m4(w,M4)
525
dpm4 = as.vector( derm4(w,M4) )
526
527
skew = pm3 / pm2^(3/2);
528
exkurt = pm4 / pm2^(2) - 3;
529
530
derskew = ( 2*(pm2^(3/2))*dpm3 - 3*pm3*sqrt(pm2)*dpm2 )/(2*pm2^3)
531
derexkurt = ( (pm2)*dpm4 - 2*pm4*dpm2 )/(pm2^3)
532
533
h = z + (1/6)*(z^2 -1)*skew
534
h = h + (1/24)*(z^3 - 3*z)*exkurt - (1/36)*(2*z^3 - 5*z)*skew^2;
535
536
MVaR = - location - h*sqrt(pm2)
537
538
derGausVaR = - as.vector(mu)- qnorm(alpha)*(0.5*as.vector(dpm2))/sqrt(pm2);
539
derMVaR = derGausVaR + (0.5*dpm2/sqrt(pm2))*( -(1/6)*(z^2 -1)*skew - (1/24)*(z^3 - 3*z)*exkurt + (1/36)*(2*z^3 - 5*z)*skew^2 )
540
derMVaR = derMVaR + sqrt(pm2)*( -(1/6)*(z^2 -1)*derskew - (1/24)*(z^3 - 3*z)*derexkurt + (1/36)*(2*z^3 - 5*z)*2*skew*derskew )
541
contrib = as.vector(w)*as.vector(derMVaR)
542
return(list( round( MVaR , precision) , round( contrib , precision ), round (contrib/MVaR , precision ) ) )
543
}
544
545
derIpower = function(power,h)
546
{
547
548
fullprod = 1;
549
550
if( (power%%2)==0 ) #even number: number mod is zero
551
{
552
pstar = power/2;
553
for(j in c(1:pstar))
554
{
555
fullprod = fullprod*(2*j)
556
}
557
I = -fullprod*h*dnorm(h);
558
559
for(i in c(1:pstar) )
560
{
561
prod = 1;
562
for(j in c(1:i) )
563
{
564
prod = prod*(2*j)
565
}
566
I = I + (fullprod/prod)*(h^(2*i-1))*(2*i-h^2)*dnorm(h)
567
}
568
}else{
569
pstar = (power-1)/2
570
for(j in c(0:pstar) )
571
{
572
fullprod = fullprod*( (2*j)+1 )
573
}
574
I = -fullprod*dnorm(h);
575
576
for(i in c(0:pstar) )
577
{
578
prod = 1;
579
for(j in c(0:i) )
580
{
581
prod = prod*( (2*j) + 1 )
582
}
583
I = I + (fullprod/prod)*(h^(2*i)*(2*i+1-h^2) )*dnorm(h)
584
}
585
}
586
return(I)
587
}
588
589
590
PortMES = function(alpha,w,mu,sigma,M3,M4,precision=4)
591
{
592
z = qnorm(alpha)
593
location = t(w)%*%mu
594
pm2 = m2(w,sigma)
595
dpm2 = as.vector( derm2(w,sigma) )
596
pm3 = m3(w,M3)
597
dpm3 = as.vector( derm3(w,M3) )
598
pm4 = m4(w,M4)
599
dpm4 = as.vector( derm4(w,M4) )
600
601
skew = pm3 / pm2^(3/2);
602
exkurt = pm4 / pm2^(2) - 3;
603
604
derskew = ( 2*(pm2^(3/2))*dpm3 - 3*pm3*sqrt(pm2)*dpm2 )/(2*pm2^3)
605
derexkurt = ( (pm2)*dpm4 - 2*pm4*dpm2 )/(pm2^3)
606
607
h = z + (1/6)*(z^2 -1)*skew
608
h = h + (1/24)*(z^3 - 3*z)*exkurt - (1/36)*(2*z^3 - 5*z)*skew^2;
609
610
derh = (1/6)*(z^2 -1)*derskew + (1/24)*(z^3 - 3*z)*derexkurt - (1/18)*(2*z^3 - 5*z)*skew*derskew
611
612
E = dnorm(h)
613
E = E + (1/24)*( Ipower(4,h) - 6*Ipower(2,h) + 3*dnorm(h) )*exkurt
614
E = E + (1/6)*( Ipower(3,h) - 3*Ipower(1,h) )*skew;
615
E = E + (1/72)*( Ipower(6,h) -15*Ipower(4,h)+ 45*Ipower(2,h) - 15*dnorm(h) )*(skew^2)
616
E = E/alpha
617
MES = - location + sqrt(pm2)*E
618
619
derMES = -mu + 0.5*(dpm2/sqrt(pm2))*E
620
derE = (1/24)*( Ipower(4,h) - 6*Ipower(2,h) + 3*dnorm(h) )*derexkurt
621
derE = derE + (1/6)*( Ipower(3,h) - 3*Ipower(1,h) )*derskew
622
derE = derE + (1/36)*( Ipower(6,h) -15*Ipower(4,h)+ 45*Ipower(2,h) - 15*dnorm(h) )*skew*derskew
623
X = -h*dnorm(h) + (1/24)*( derIpower(4,h) - 6*derIpower(2,h) -3*h*dnorm(h) )*exkurt
624
X = X + (1/6)*( derIpower(3,h) - 3*derIpower(1,h) )*skew
625
X = X + (1/72)*( derIpower(6,h) - 15*derIpower(4,h) + 45*derIpower(2,h) + 15*h*dnorm(h) )*skew^2
626
derE = derE+derh*X # X is a scalar
627
derE = derE/alpha
628
derMES = derMES + sqrt(pm2)*derE
629
contrib = as.vector(w)*as.vector(derMES)
630
return(list( round( MES , precision ) , round( contrib , precision ), round( contrib/MES, precision )) )
631
}
632
633
634
operPortMES = function(alpha,w,mu,sigma,M3,M4,precision=4)
635
{
636
z = qnorm(alpha)
637
location = t(w)%*%mu
638
pm2 = m2(w,sigma)
639
dpm2 = as.vector( derm2(w,sigma) )
640
pm3 = m3(w,M3)
641
dpm3 = as.vector( derm3(w,M3) )
642
pm4 = m4(w,M4)
643
dpm4 = as.vector( derm4(w,M4) )
644
645
skew = pm3 / pm2^(3/2);
646
exkurt = pm4 / pm2^(2) - 3;
647
648
derskew = ( 2*(pm2^(3/2))*dpm3 - 3*pm3*sqrt(pm2)*dpm2 )/(2*pm2^3)
649
derexkurt = ( (pm2)*dpm4 - 2*pm4*dpm2 )/(pm2^3)
650
651
h = z + (1/6)*(z^2 -1)*skew
652
h = h + (1/24)*(z^3 - 3*z)*exkurt - (1/36)*(2*z^3 - 5*z)*skew^2;
653
I1 = Ipower(1,h); I2 = Ipower(2,h); I3 = Ipower(3,h); I4 = Ipower(4,h); I6 = Ipower(6,h);
654
655
derh = (1/6)*(z^2 -1)*derskew + (1/24)*(z^3 - 3*z)*derexkurt - (1/18)*(2*z^3 - 5*z)*skew*derskew
656
657
E = dnorm(h)
658
E = E + (1/24)*( I4 - 6*I2 + 3*dnorm(h) )*exkurt
659
E = E + (1/6)*( I3 - 3*I1 )*skew;
660
E = E + (1/72)*( I6 -15*I4+ 45*I2 - 15*dnorm(h) )*(skew^2)
661
E = E/alpha
662
663
MES = - location - sqrt(pm2)*min(-E,h)
664
665
if(-E<=h){
666
derMES = -mu + 0.5*(dpm2/sqrt(pm2))*E
667
derE = (1/24)*( I4 - 6*I2 + 3*dnorm(h) )*derexkurt
668
derE = derE + (1/6)*( I3 - 3*I1 )*derskew
669
derE = derE + (1/36)*( I6 -15*I4 + 45*I2 - 15*dnorm(h) )*skew*derskew
670
X = -h*dnorm(h) + (1/24)*( derIpower(4,h) - 6*derIpower(2,h) -3*h*dnorm(h) )*exkurt
671
X = X + (1/6)*( derIpower(3,h) - 3*derIpower(1,h) )*skew
672
X = X + (1/72)*( derIpower(6,h) - 15*derIpower(4,h) + 45*derIpower(2,h) + 15*h*dnorm(h) )*skew^2
673
derE = derE+derh*X # X is a scalar
674
derE = derE/alpha
675
derMES = derMES + sqrt(pm2)*derE }else{
676
derMES = -mu - 0.5*(dpm2/sqrt(pm2))*h - sqrt(pm2)*derh ; }
677
contrib = as.vector(w)*as.vector(derMES)
678
return(list( round( MES, precision) , round( contrib , precision ) , round(contrib/MES,precision) ) )
679
}
680
681
682
centeredmoment = function(series,power)
683
{
684
location = mean(series);
685
out = sum( (series-location)^power )/length(series);
686
return(out);
687
}
688
689
operMES = function(series,alpha,r)
690
{
691
z = qnorm(alpha)
692
location = mean(series);
693
m2 = centeredmoment(series,2)
694
m3 = centeredmoment(series,3)
695
m4 = centeredmoment(series,4)
696
skew = m3 / m2^(3/2);
697
exkurt = m4 / m2^(2) - 3;
698
699
h = z + (1/6)*(z^2 -1)*skew
700
if(r==2){ h = h + (1/24)*(z^3 - 3*z)*exkurt - (1/36)*(2*z^3 - 5*z)*skew^2};
701
702
MES = dnorm(h)
703
MES = MES + (1/24)*( Ipower(4,h) - 6*Ipower(2,h) + 3*dnorm(h) )*exkurt
704
MES = MES + (1/6)*( Ipower(3,h) - 3*Ipower(1,h) )*skew;
705
MES = MES + (1/72)*( Ipower(6,h) -15*Ipower(4,h)+ 45*Ipower(2,h) - 15*dnorm(h) )*(skew^2)
706
MES = - location - (sqrt(m2))*min( -MES/alpha , h )
707
return(MES)
708
}
709
710
TwoVarPlot <- function(xvar, y1var, y2var, labels, noincs = 5,marks=c(1,2), legpos, leglabs, title)
711
{
712
# https://stat.ethz.ch/pipermail/r-help/2000-September/008182.html
713
714
# plots an x y1 y2 using left and right axes for the different y's
715
# rescales y2 to fit in the same space as y1
716
717
# noincs - no of divisions in the axis labels
718
# marks - type of marker for each y
719
# legpos - legend position
720
# leglabs - legend labels
721
722
# rescale to fit on same axis
723
scaledy2var <- (y2var - min(y2var)) / (max(y2var) - min(y2var))
724
scaledy2var <- (scaledy2var * (max(y1var) - min(y1var))) + min(y1var)
725
726
# plot it up and add the points
727
plot(xvar, y1var, xlab=labels[1], ylab="", axes=F, pch=marks[1],main=title,type="l")
728
lines(xvar, scaledy2var, lty=3 )
729
730
# make up some labels and positions
731
y1labs <- round(seq(min(y1var), max(y1var), length=noincs),2)
732
733
# convert these to the y2 axis scaling
734
y2labs <- (y1labs - min(y1var)) / (max(y1var) - min(y1var))
735
y2labs <- (y2labs * (max(y2var) - min(y2var))) + min(y2var)
736
y2labs <- round(y2labs, 2)
737
738
axis(1)
739
axis(2, at=y1labs, labels=y1labs)
740
axis(4, at=y1labs, labels=y2labs)
741
mtext(labels[3], side=4, line=2)
742
mtext(labels[2], side=2, line=2)
743
box()
744
745
legend( legend=leglabs, lty = c(1,3), bty="o", x=legpos)
746
}
747
748
749
750