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 June 2018

```
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-3,3.1, step = 0.1) # Python's arange excludes the last value
plt.plot(x, stats.norm.cdf(x))
plt.show()
plt.close()
```

Last updated June 2018

```
x = collect(linspace(-3, 3, 61))
using Plots;
using Distributions;
return plot(x, cdf.(Normal(0,1), x))
```

Last updated June 2018

```
import numpy as np
np.random.seed(12) # set seed
S = 10
print (np.random.uniform(size=S))
print (np.random.normal(size=S))
print (np.random.standard_t(df=4,size=S))
```

Last updated June 2018

```
srand(12); # set seed
S = 10;
println(rand(Uniform(0,1), S)) # alternatively, rand(S)
println(rand(Normal(0,1), S)) # alternatively, randn(S)
println(rand(TDist(4), S))
```

Last updated June 2018

```
import numpy as np
yield_c = [5.00, 5.69, 6.09, 6.38, 6.61,
6.79, 6.94, 7.07, 7.19, 7.30] # yield curve
T = len(yield_c)
r = 0.07 # initial yield rate
Par = 10 # par value
coupon = r * Par # coupon payments
cc = [coupon] * 10 # vector of cash flows
cc[9] += Par # add par to cash flows
P=np.sum(cc/(np.power((1+np.divide(yield_c,100)),
list(range(1,T+1))))) # calc price
print(P)
```

Last updated June 2018

```
yield_c = [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_c)
r = 0.07 # initial yield rate
Par = 10 # par value
coupon = r * Par # coupon payments
cc = repeat([coupon], outer = 10) # vector of cash flows
cc[10] += Par # add par to cash flows
P = sum(cc./((1+yield_c/100).^(1:T))) # calc price
```

Last updated June 2018

```
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(12) # set seed
sigma = 1.5 # daily yield volatility
S = 8 # number of simulations
r = np.random.normal(0,sigma,size=S) # generate random numbers
ysim = np.zeros([T,S])
for i in range(S):
ysim[:,i] = yield_c + r[i]
plt.plot(ysim)
plt.show()
plt.close()
```

Last updated June 2018

```
srand(12) # set seed
sigma = 1.5 # daily yield volatility
S = 8 # number of simulations
r = rand(Normal(0,1), S) # generate random numbers
ysim = fill!(Array{Float64}(T,S), NaN)
for i in range(1, S)
ysim[:,i] = yield_c + r[i]
end
using Plots;
plot(ysim)
```

Last updated June 2018

```
import numpy as np
import matplotlib.pyplot as plt
S = 8
SP = np.zeros([S])
for i in range(S): # S simulations
SP[i] = np.sum(cc/((1+ysim[:,i]/100)**T))
SP -= (np.mean(SP) - P) # correct for mean
plt.bar(range(1,S+1), SP)
plt.show()
plt.close()
S = 50000
r = np.random.normal(0, sigma, size = S)
ysim = np.zeros([T,S])
for i in range(S):
ysim[:,i] = yield_c + r[i]
SP = np.zeros([S])
for i in range(S):
SP[i] = np.sum(cc/((1+ysim[:,i]/100)**T))
SP -= (np.mean(SP) - P)
plt.hist(SP, bins = 30, range = (7, 13), density = True)
fitted_norm=stats.norm.pdf(np.linspace(7,13,30),
np.mean(SP),np.std(SP,ddof=1))
plt.plot(np.linspace(7,13,30), fitted_norm)
plt.show()
plt.close()
```

Last updated June 2018

```
SP = fill!(Array{Float64}(S,1), NaN)
for i in range(1,S) # S simulations
SP[i] = sum(cc./(1+ysim[:,i]./100).^T)
end
SP -= (mean(SP) - P) # correct for mean
using Plots;
bar(SP)
S = 50000
r = randn(S) * sigma
ysim = fill!(Array{Float64}(T,S), NaN)
for i in range(1, S)
ysim[:,i] = yield_c + r[i]
end
SP = fill!(Array{Float64}(S,1), NaN)
for i in range(1,S)
SP[i] = sum(cc./(1+ysim[:,i]./100).^T)
end
SP -= (mean(SP) - P)
using Plots;
histogram(SP,nbins=100,normed=true,xlims=(7,13))
res = fit_mle(Normal, SP)
plot!(Normal(res.μ, res.σ), linewidth = 4)
```

Last updated June 2018

```
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)
print (f)
```

Last updated June 2018

```
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 June 2018

```
import numpy as np
np.random.seed(12) # set seed
S = 10**6 # number of simulations
F = P0 * np.exp(r * T) # futures price
ysim=np.random.normal(-0.5*sigma**2*T,
sigma*np.sqrt(T),size=S) # sim returns, lognorm corrected
F = F * np.exp(ysim) # sim futures price
SP = F - X # payoff
SP[SP < 0] = 0 # set negative outcomes to zero
fsim = SP * np.exp(-r * T) # discount
call_sim = mean(fsim) # simulated price
print(call_sim)
```

Last updated June 2018

```
srand(12) # set seed
S = 10^6 # number of simulations
F = P0 * exp(r * T) # futures price
ysim = randn(S)*sigma*sqrt(T)-0.5*sigma^2*T # 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 * T) # discount
call_sim = mean(fsim) # simulated price
```

Last updated June 2018

```
import numpy as np
import matplotlib.pyplot as plt
plt.hist(F, bins = 60, range = (20,80), density = True)
fitted_norm=stats.norm.pdf(np.linspace(20,80,60),np.mean(F),np.std(F,ddof=1))
plt.plot(np.linspace(20,80,60), fitted_norm)
plt.axvline(x=X, color='k')
plt.show()
plt.close()
plt.hist(fsim, bins = 60, range = (0, 35), density = True)
plt.axvline(x=f['Call'], color='k')
plt.show()
plt.close()
```

Last updated June 2018

```
using Plots;
histogram(F, bins = 100, normed = true, xlims = (20,80))
res = fit_mle(Normal, F)
plot!(Normal(res.μ, res.σ), linewidth = 4)
vline!([X], linewidth = 4, color = "black")
histogram(fsim, bins = 110, normed = true, xlims = (0,35))
vline!([f["Call"]], linewidth = 4, color = "black")
```

Last updated June 2018

```
import numpy as np
np.random.seed(1) # set seed
S = 10**7 # number of simulations
s2 = 0.01**2 # daily variance
p = 0.01 # probability
r = 0.05 # annual riskfree rate
P = 100 # price today
ysim=np.random.normal(r/365-0.5*s2,np.sqrt(s2),size=S) # sim returns
Psim = P * np.exp(ysim) # sim future prices
q = np.sort(Psim - P) # simulated P/L
VaR1 = -q[int(p*S) - 1]
print(VaR1)
```

Last updated June 2018

```
srand(1) # set seed
S = 10^7 # 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) * 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[convert(Int, p*S)]
```

Last updated June 2018

```
import numpy as np
T = 0.25 # time to expiration
X = 100 # strike price
sigma = np.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 = np.sort(fsim['Call']-f['Call']) # simulated P/L
VaR2 = -q[int(p*S) - 1]
print(VaR2)
```

Last updated June 2018

```
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[convert(Int, p*S)]
```

Last updated June 2018

```
import numpy as np
X1 = 100
X2 = 110
f1 = bs(X1, P, r, sigma, T)
f2 = bs(X2, P, r, sigma, T)
f2sim = bs(X2, Psim, r, sigma, T-(1/365))
f1sim = bs(X1, Psim, r, sigma, T-(1/365))
q = np.sort(f1sim['Call'] + f2sim['Put'] + Psim - f1['Call'] - f2['Put'] - P)
VaR3 = -q[int(p*S) - 1]
print(VaR3)
```

Last updated June 2018

```
X1 = 100
X2 = 110
f1 = bs(X1,P,r,sigma,T)
f2 = bs(X2,P,r,sigma,T)
f2sim = bs(X2,Psim,r,sigma,T-(1/365))
f1sim = bs(X1,Psim,r,sigma,T-(1/365))
q = sort(f1sim["Call"] + f2sim["Put"] + Psim - f1["Call"] - f2["Put"] - P)
VaR2 = -q[convert(Int, p*S)]
```

Last updated June 2018

```
import numpy as np
np.random.seed(12) # set seed
mu = np.transpose([r/365, r/365]) # return mean
Sigma = np.matrix([[0.01, 0.0005],[0.0005, 0.02]]) # covariance matrix
y = np.random.multivariate_normal(mu, Sigma, size = S) # simulated returns
```

Last updated June 2018

```
using Distributions;
srand(12); # set seed
mu = Vector([r/365, r/365]); # return mean
Sigma = [0.01 0.0005; 0.0005 0.02]; # covariance matrix
y = rand(MvNormal(mu,Sigma), S); # simulated returns
```

Last updated June 2018

```
import numpy as np
P = np.asarray([100, 50]) # prices
x = np.asarray([1, 1]) # number of assets
Port = np.matmul(P, x) # portfolio at t
Psim=np.matlib.repmat(P,S,1)*np.exp(y) # simulated prices
PortSim = np.matmul(Psim, x) # simulated portfolio value
q = np.sort(PortSim - Port) # simulated P/L
VaR4 = -q[int(p*S) - 1]
print(VaR4)
```

Last updated June 2018

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

Last updated June 2018

```
import numpy as np
f = bs(P[1], P[1], r, sigma, T)
fsim = bs(P[1], Psim[:,1], r, sigma, T-(1/365))
q = np.sort(fsim['Call'] + Psim[:,0] - f['Call'] - P[0])
VaR5 = -q[int(p*S) - 1]
print(VaR5)
```

Last updated June 2018

```
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[convert(Int, p * S)]
```