# Chapter 6. Analytical Value–at–Risk for Options and Bonds (in MATLAB/Julia)

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.

##### Listing 6.1/6.2: Black-Scholes function in MATLAB Last updated 2011

%% To run this code block in Jupyter notebook:
%% delete all lines above the line with file bs.m, then run
%%file bs.m
function  res = bs(K,P,r,sigma,T)
d1 = (log(P./K)+(r+(sigma^2)/2)*T)./(sigma*sqrt(T));
d2 = d1 - sigma*sqrt(T);
res.Call = P.*normcdf(d1,0,1)-K.*exp(-r*T).*normcdf(d2,0,1);
res.Put = K.*exp(-r*T).*normcdf(-d2,0,1)-P.*normcdf(-d1,0,1);
res.Delta.Call = normcdf(d1,0,1);
res.Delta.Put = res.Delta.Call -1;
res.Gamma = normpdf(d1,0,1)./(P*sigma*sqrt(T));
end

##### Listing 6.1/6.2: Black-Scholes function in Julia Last updated June 2018

function bs(X, P, r, sigma, T)
d1 = (log.(P/X) + (r + 0.5 * sigma^2)*T)/(sigma * sqrt(T))
d2 = d1 - sigma * sqrt(T)
Call = P .* cdf.(Normal(0,1), d1) - X * exp(-r * T) .* cdf.(Normal(0,1), d2)
Put = X * exp(-r * T) .* cdf.(Normal(0,1),-d2) - P .* cdf.(Normal(0,1), -d1)
Delta_Call = cdf.(Normal(0,1), d1)
Delta_Put = Delta_Call - 1
Gamma = pdf.(Normal(0,1), d1) ./ (P * sigma * sqrt(T))
return Dict("Call" => Call, "Put" => Put, "Delta_Call" => Delta_Call, "Delta_Put" => Delta_Put, "Gamma" => Gamma)
end


##### Listing 6.3/6.4: Black-Scholes in MATLAB Last updated 2011

f=bs(90,100,0.05,0.2,0.5)

##### Listing 6.3/6.4: Black-Scholes in Julia Last updated June 2018

f = bs(90, 100, 0.05, 0.2, 0.5)