# Chapter 6. Analytical Value--at--Risk for Options and Bonds

##### Listing 6.1: Black-Scholes function in R Last edited: 2011

bs = function(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*pnorm(d1, mean = 0, sd = 1) - X*exp(-r*(T))*pnorm(d2, mean = 0, sd = 1)
Put = X*exp(-r*(T))*pnorm(-d2, mean = 0, sd = 1) - P*pnorm(-d1, mean = 0, sd = 1)
Delta.Call = pnorm(d1, mean = 0, sd = 1)
Delta.Put = Delta.Call - 1
Gamma = dnorm(d1, mean = 0, sd = 1)/(P*sigma*sqrt(T))
return(list(Call=Call,Put=Put,Delta.Call=Delta.Call,Delta.Put=Delta.Put,Gamma=Gamma))
}

##### Listing 6.2: Black-Scholes function in Matlab Last edited: 2011

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.3: Black-Scholes in R Last edited: August 2016

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

##### Listing 6.4: Black-Scholes in Matlab Last edited: 2011

>> f=bs(90,100,0.05,0.2,0.5)
f =
Call: 13.4985
Put: 1.2764
Delta: [1x1 struct]
Gamma: 0.0172
>> f.Delta
ans =
Call: 0.8395
Put: -0.1605