Copyright 2011, 2016, 2018 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: https://www.gnu.org/licenses/.

The original 2011 R code will not fully work on a recent R because there have been some changes to libraries. The latest version of the Matlab code only uses functions from Matlab toolboxes.

The GARCH functionality in the econometric toolbox in Matlab is trying to be too clever, but can't deliver and could well be buggy. If you want to try that, here are the docs (estimate). Besides, it can only do univariate GARCH and so can't be used in Chapter 3. Kevin Sheppard's MFE toolbox is much better, while not as user friendly, it is much better written and is certainly more comprehensive. It can be downloaded here and the documentation here is quite detailed.

Last updated 2011

```
x=seq(-3,3,by=0.1)
plot(x,pnorm(x),type="l")
```

Last updated 2011

```
x=-3:0.1:3;
plot(x,normcdf(x))
```

Last updated 2011

```
set.seed(12) # set seed
S=10
runif(S)
rnorm(S)
rt(S,4)
```

Last updated August 2016

```
rng default; % set seed
S=10;
rand(S,1)
randn(S,1)
trnd(4,S,1)
```

Last updated August 2016

```
yield=c(5.00, 5.69, 6.09, 6.38, 6.61,
6.79, 6.94, 7.07, 7.19, 7.30) # yield curve
TT=length(yield)
r=0.07 # initial yield rate
Par=10 # par value
coupon=r*Par # coupon payments
cc=1:10*0+coupon # vector of cash flows
cc[10]=cc[10]+Par # add par to cash flows
P=sum(cc/((1+yield/100)^(1:TT))) # calculate price
print(P)
```

Last updated 2011

```
yield = [5.00 5.69 6.09 6.38 6.61...
6.79 6.94 7.07 7.19 7.30]; % yield curve
T = length(yield);
r=0.07; % initial yield rate
Par=10; % par value
coupon=r*Par; % coupon payments
cc=zeros(1,T)+coupon; % vector of cash flows
cc(10)=cc(10)+Par; % add par to cash flows
P=sum(cc./((1+yield./100).^(1:T))) % calculate price
```

Last updated August 2016

```
set.seed(12) # set seed
sigma = 1.5 # daily yield volatiltiy
S = 8 # number of simulations
r = rnorm(S,0,sigma) # generate random numbers
ysim = matrix(nrow=TT,ncol=S)
for (i in 1:S) ysim[,i]=yield+r[i]
matplot(ysim,type='l')
```

Last updated 2011

```
randn('state',123); % set the seed
sigma = 1.5; % daily yield volatility
S = 8; % number of simulations
r = randn(1,S)*sigma; % generate random numbers
ysim=nan(T,S);
for i=1:S
ysim(:,i)=yield+r(i);
end
ysim=repmat(yield',1,S)+repmat(r,T,1);
plot(ysim)
```

Last updated August 2016

```
SP = vector(length=S)
for (i in 1:S){ # S simulations
SP[i] = sum(cc/((1+ysim[,i]/100)^(TT)))
}
SP = SP-(mean(SP) - P) # correct for mean
barplot(SP)
hist(SP,probability=TRUE)
x=seq(6,16,length=100)
lines(x, dnorm(x, mean = mean(SP), sd = sd(SP)))
```

Last updated 2011

```
SP = nan(S,1);
for s = 1:S % S simulations
SP(s) = sum(cc./(1+ysim(:,s)'./100).^((1:T)));
end
SP = SP-(mean(SP) - P); % correct for mean
bar(SP)
```

Last updated August 2016

```
P0 = 50 # initial spot price
sigma = 0.2 # annual volatility
r = 0.05 # annual interest
TT = 0.5 # time to expiration
X = 40 # strike price
f = bs(X,P0,r,sigma,TT) # analytical call price
## this calculation uses the Black-Scholes pricing function (Listing 6.1/6.2)
print(f)
```

Last updated 2011

```
P0 = 50; % initial spot price
sigma = 0.2; % annual volatility
r = 0.05; % annual interest
T = 0.5; % time to expiration
X = 40; % strike price
f = bs(X,P0,r,sigma,T) % analytical call price
%% this calculation uses the Black-Scholes pricing function (Listing 6.1/6.2)
```

Last updated August 2016

```
set.seed(12) # set seed
S = 1e6 # number of simulations
F = P0*exp(r*TT) # futures price
ysim = rnorm(S,-0.5*sigma^2*TT,sigma*sqrt(TT)) # sim returns, lognorm corrected
F=F*exp(ysim) # sim futures price
SP = F-X # payoff
SP[SP<0] = 0 # set negative outcomes to zero
fsim = SP*exp(-r*TT) # discount
call_sim = mean(fsim) # simulated price
print(call_sim)
```

Last updated 2011

```
randn('state',0); % set seed
S = 1e6; % number of simulations
F = P0*exp(r*T); % futures price
ysim=randn(S,1)*sigma*sqrt(T)-0.5*T*sigma^2; % sim returns, lognorm corrected
F=F*exp(ysim); % sim futures price
SP = F-X; % payoff
SP(find(SP < 0)) = 0; % set negative outcomes to zero
fsim =SP*exp(-r*T) ; % discount
mean(fsim) % simulated price
```

Last updated 2011

```
hist(F,probability=TRUE,ylim=c(0,0.06))
x=seq(min(F),max(F),length=100)
lines(x, dnorm(x, mean = mean(F), sd = sd(SP)))
hist(fsim,nclass=100,probability=TRUE)
```

Last updated 2011

```
subplot(1,2,1)
histfit(F);
subplot(1,2,2)
hist(fsim,100);
```

Last updated 2011

```
set.seed(1) # set seed
S = 1e7 # number of simulations
s2 = 0.01^2 # daily variance
p = 0.01 # probability
r = 0.05 # annual riskfree rate
P = 100 # price today
ysim = rnorm(S,r/365-0.5*s2,sqrt(s2)) # sim returns
Psim = P*exp(ysim) # sim future prices
q = sort(Psim-P) # simulated P/L
VaR1 = -q[p*S]
print(VaR1)
```

Last updated 2011

```
randn('state',0); % set seed
S = 1e7; % number of simulations
s2 = 0.01^2; % daily variance
p = 0.01; % probability
r = 0.05; % annual riskfree rate
P = 100; % price today
ysim = randn(S,1)*sqrt(s2)+r/365-0.5*s2; % sim returns
Psim = P*exp(ysim); % sim future prices
q = sort(Psim-P); % simulated P/L
VaR1 = -q(S*p)
```

Last updated August 2016

```
TT = 0.25; # time to expiration
X = 100; # strike price
sigma = sqrt(s2*250); # annual volatility
f = bs(X,P,r,sigma,TT) # analytical call price
fsim = bs(X,Psim,r,sigma,TT-(1/365)) # sim option prices
q = sort(fsim$Call-f$Call) # simulated P/L
VaR2 = -q[p*S]
print(VaR2)
```

Last updated 2011

```
T = 0.25; % time to expiration
X = 100; % strike price
sigma = sqrt(s2*250); % annual volatility
f = bs(X,P,r,sigma,T); % analytical call price
fsim=bs(X,Psim,r,sigma,T-(1/365)); % sim option prices
q = sort(fsim.Call-f.Call); % simulated P/L
VaR2 = -q(p*S)
```

Last updated August 2016

```
X1 = 100
X2 = 110
f1 = bs(X1,P,r,sigma,TT)
f2 = bs(X2,P,r,sigma,TT)
f2sim = bs(X2,Psim,r,sigma,TT-(1/365))
f1sim = bs(X1,Psim,r,sigma,TT-(1/365))
q = sort(f1sim$Call+f2sim$Put+Psim-f1$Call-f2$Put-P);
VaR3 = -q[p*S]
print(VaR3)
```

Last updated 2011

```
X1 = 100;
X2 = 110;
f1 = bs(X1,P,r,sigma,T);
f2 = bs(X2,P,r,sigma,T);
f1sim=bs(X1,Psim,r,sigma,T-(1/365));
f2sim=bs(X2,Psim,r,sigma,T-(1/365));
q = sort(f1sim.Call+f2sim.Put+Psim-f1.Call-f2.Put-P);
VaR3 = -q(p*S)
```

Last updated 2011

```
library (MASS)
set.seed(12) # set seed
mu = c(r/365,r/365) # return mean
Sigma = matrix(c(0.01,0.0005,0.0005,0.02),ncol=2) # covariance matrix
y = mvrnorm(S,mu,Sigma) # simulated returns
```

Last updated 2011

```
randn('state',12) % set seed
mu = [r/365 r/365]'; % return mean
Sigma=[0.01 0.0005; 0.0005 0.02]; % covariance matrix
y = mvnrnd(mu,Sigma,S); % simulated returns
```

Last updated 2011

```
K=2
P = c(100,50) # prices
x = c(1,1) # number of assets
Port = P %*% x # portfolio at t
Psim = matrix(t(matrix(P,K,S)),ncol=K)*exp(y) # simulated prices
PortSim = Psim %*% x # simulated portfolio value
q = sort(PortSim-Port[1,1]) # simulated P/L
VaR4 = -q[S*p]
print(VaR4)
```

Last updated 2011

```
K = 2;
P = [100 50]'; % prices
x = [1 1]'; % number of assets
Port = P'*x; % portfolio at t
Psim = repmat(P,1,S)' .*exp(y); % simulated prices
PortSim=Psim * x; % simulated portfolio value
q = sort(PortSim-Port); % simulated P/L
VaR4 = -q(S*p)
```

Last updated August 2016

```
f = bs(P[2],P[2],r,sigma,TT)
fsim = bs(P[2],Psim[,2],r,sigma,TT-(1/365))
q = sort(fsim$Call+Psim[,1]-f$Call-P[1]);
VaR5 = -q[p*S]
print(VaR5)
```

Last updated 2011

```
f = bs(P(2),P(2),r,sigma,T);
fsim=bs(P(2),Psim(:,2),r,sigma,T-(1/365));
q = sort(fsim.Call+Psim(:,1)-f.Call-P(1));
VaR5 = -q(p*S)
```