R and Matlab Chapter 5. Implementing Risk Forecasts

# Chapter 5. Implementing Risk Forecasts

### R and Matlab

Copyright 2011 - 2023 Jon Danielsson. This code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The GNU General Public License is available at: www.gnu.org/licenses.

##### Listing 5.1/5.2
p = read.csv('stocks.csv')
y = apply(log(p),2,diff)
portfolio_value = 1000
p = 0.01

##### Listing 5.1/5.2
stocks = csvread('stocks.csv',1,0);
p1 = stocks(:,1);             % consider first two stocks
p2 = stocks(:,2);
y1=diff(log(p1));             % convert prices to returns
y2=diff(log(p2));
y=[y1 y2];
T=length(y1);
value = 1000;                 % portfolio value
p = 0.01;                     % probability


##### Univariate HS in R
y1 = y[,1]                     # select one asset
ys = sort(y1)                  # sort returns
op = ceiling(length(y1)*p)     # p percent smallest, rounded up
VaR1 = -ys[op]*portfolio_value
print(VaR1)

##### % Univariate HS VaR in MATLAB
ys = sort(y1);   % sort returns
op = ceil(T*p);  % p percent smallest, rounded up to meet VaR probability requirement
VaR1 = -ys(op)*value


##### Multivariate HS in R
w = matrix(c(0.3,0.2,0.5))   # vector of portfolio weights
yp = y %*% w                 # obtain portfolio returns
yps = sort(yp)
VaR2 = -yps[op]*portfolio_value
print(VaR2)

##### % Multivariate HS VaR in MATLAB
w = [0.3; 0.7];    % vector of portfolio weights
yp = y*w;          % portfolio returns
yps = sort(yp);
VaR2 = -yps(op)*value


##### Univariate ES in R
ES1 = -mean(ys[1:op])*portfolio_value
print(ES1)

##### % Univariate ES in MATLAB
ES1 = -mean(ys(1:op))*value


##### Normal VaR in R
sigma = sd(y1) # estimate volatility
VaR3 = -sigma * qnorm(p) * portfolio_value
print(VaR3)

##### % Normal VaR in MATLAB
sigma = std(y1); % estimate volatility
VaR3 = -sigma * norminv(p) * value


##### Portfolio normal VaR in R
sigma = sqrt(t(w) %*% cov(y) %*% w) # portfolio volatility
VaR4 = -sigma * qnorm(p)*portfolio_value
print(VaR4)

##### % Portfolio normal VaR in MATLAB
sigma = sqrt(w' * cov(y) * w); % portfolio volatility
VaR4 = - sigma * norminv(p) *  value


##### Student-t VaR in R
library(QRM)
scy1 = (y1)*100                     # scale the returns
res = fit.st(scy1)
sigma1 = unname(res$par.ests['sigma']/100) # rescale the volatility nu = unname(res$par.ests['nu'])
VaR5 = - sigma1 * qt(df=nu,p=p) *  portfolio_value
print(VaR5)

##### % Student-t VaR in MATLAB
scy1=y1*100;          % scale the returns
res=mle(scy1,'distribution','tlocationscale');
sigma1 = res(2)/100;  % rescale the volatility
nu = res(3);
VaR5 = - sigma1 * tinv(p,nu) * value


##### Normal ES in R
sigma = sd(y1)
ES2 = sigma*dnorm(qnorm(p))/p * portfolio_value
print(ES2)

##### % Normal ES in MATLAB
sigma = std(y1);
ES2=sigma*normpdf(norminv(p))/p * value


##### Direct integration ES in R
VaR = -qnorm(p)
integrand = function(q){q*dnorm(q)}
ES = -sigma*integrate(integrand,-Inf,-VaR)$value/p*portfolio_value print(ES)  ##### Listing 5.17/5.18 ##### % Direct integration ES in MATLAB VaR = -norminv(p); ES = -sigma*quad(@(q) q.*normpdf(q),-6,-VaR)/p*value  ##### Listing 5.19/5.20 ##### MA normal VaR in R WE=20 for (t in seq(length(y1)-5,length(y1))){ t1=t-WE+1 window= y1[t1:t] # estimation window sigma=sd(window) VaR6 = -sigma * qnorm(p) * portfolio_value print(VaR6) }  ##### Listing 5.19/5.20 ##### % MA normal VaR in MATLAB WE=20; for t=T-5:T t1=t-WE+1; window=y1(t1:t); % estimation window sigma=std(window); VaR6 = -sigma * norminv(p) * value end  ##### Listing 5.21/5.22 ##### EWMA VaR in R lambda = 0.94 s11 = var(y1) # initial variance, using unconditional for (t in 2:length(y1)){ s11 = lambda * s11 + (1-lambda) * y1[t-1]^2 } VaR7 = -qnorm(p) * sqrt(s11) * portfolio_value print(VaR7)  ##### Listing 5.21/5.22 ##### % EWMA VaR in MATLAB lambda = 0.94; s11 = var(y1(1:30)); % initial variance for t = 2:T s11 = lambda * s11 + (1-lambda) * y1(t-1)^2; end VaR7 = -norminv(p) * sqrt(s11) * value  ##### Listing 5.23/5.24 ##### Three-asset EWMA VaR in R s = cov(y) # initial covariance for (t in 2:dim(y)){ s = lambda*s + (1-lambda)*y[t-1,] %*% t(y[t-1,]) } sigma = sqrt(t(w) %*% s %*% w) # portfolio vol VaR8 = -sigma * qnorm(p) * portfolio_value print(VaR8)  ##### Listing 5.23/5.24 ##### % Two-asset EWMA VaR in MATLAB s = cov(y); % initial covariance for t = 2:T s = lambda * s + (1-lambda) * y(t-1,:)' * y(t-1,:); end sigma = sqrt(w' * s * w); % portfolio vol VaR8 = - sigma * norminv(p) * value  ##### Listing 5.25/5.26 ##### Univariate GARCH in R library(rugarch) spec = ugarchspec(variance.model = list( garchOrder = c(1, 1)), mean.model = list( armaOrder = c(0,0),include.mean = FALSE)) res = ugarchfit(spec = spec, data = y1, solver = "hybrid") omega = res@fit$coef['omega']
alpha = res@fit$coef['alpha1'] beta = res@fit$coef['beta1']
sigma2 = omega + alpha * tail(y1,1)^2 + beta * tail(res@fit\$var,1)
VaR9 = -sqrt(sigma2) * qnorm(p) * portfolio_value
names(VaR9)="VaR"
print(VaR9)

##### % GARCH in MATLAB
[parameters,ll,ht]=tarch(y1,1,0,1);
omega = parameters(1)
alpha = parameters(2)
beta = parameters(3)
sigma2 = omega + alpha*y1(end)^2 + beta*ht(end) % calc sigma2 for t+1
VaR9 = -sqrt(sigma2) * norminv(p) * value


##### Financial Risk Forecasting
Market risk forecasting with R, Julia, Python and Matlab. Code, lecture slides, implementation notes, seminar assignments and questions.