## Merton Model – R Code

This is an impelementation of the Merton model in R. As an output we get the asset value and volatility as well as estimates for the probability of default and recovery rate.

```## Merton Model

# clear environment and console
rm(list = ls())
cat("\014")

# install and load required packages
install.packages('rootSolve')
library(rootSolve)

# inputs
Ve = 5 # value of equity
vol = .3 # volatility of equity
r = .06 # risk-free rate
t = 5 # time horizon
D = 3 # value of debt

merton = function(x)
{c(f1 = (pnorm((log(x[1] / D) + (r + 0.5 * (x[2] ^ 2)) * t)/ (x[2] * sqrt(t))) * x[2] * x[1]) - (Ve * vol),
f2 = (x[1] * pnorm((log(x[1] / D) + (r + 0.5 * (x[2] ^ 2)) * t) / (x[2] * sqrt(t))) - D * exp(-r * t) *
pnorm(((log(x[1] / D) + (r + 0.5 * (x[2] ^ 2)) * t) / (x[2] * sqrt(t))) - x[2] * sqrt(t))) - Ve)}

roots = multiroot(merton, c(15, 0.2))

# outputs
v0 = roots\$root[1] # value of assets
volv = roots\$root[2] # volatility of assets
v0; volv

# calculate probability of default & recovery rate
market_val = v0 - Ve
payment = D * exp(-r * t)

prob_default = pnorm(-(((log(v0 / D) + (r + 0.5 * (volv ^ 2)) * t) / (volv * sqrt(t))) - volv * sqrt(t)))
prob_default

expected_loss = (payment - market_val) / (payment)
recovery = 1 - (expected_loss / prob_default)
recovery
```