---
title: "Margrabe formula - example"
author: "Beata Stehlikova, Financial derivatives course"
output: html_document
---
# Margrabe formula - example
### Beata Stehlikova, Financial derivatives course

Library `quantmod` provides a convenient way of obtaining stock price data. In this example, we are going to use AAPL and IBM stock prices from the last year:

```{r, include=FALSE}
library(quantmod)
getSymbols("AAPL", from="2014-01-01", to="2015-01-01")
getSymbols("IBM", from="2014-01-01", to="2015-01-01")
```

```{r, eval=FALSE}
library(quantmod)
getSymbols("AAPL", from="2014-01-01", to="2015-01-01")
getSymbols("IBM", from="2014-01-01", to="2015-01-01")
```

We use adjusted close prices:
```{r}
AAPL<-AAPL$AAPL.Adjusted
IBM<-IBM$IBM.Adjusted
```
and plot them:
```{r}
plot(IBM, ylim=c(min(as.numeric(AAPL),as.numeric(IBM)), 1.35*max(as.numeric(AAPL),as.numeric(IBM))), 
     main="IBM and AAPL stock");
lines(AAPL, col="green")
legend("topright",legend=c("IBM","AAPL"),col=c("black","green"), lty = c(1, 1))
```

Our question is: **What is the price of the option with a payoff
`max(S(IBM)-S(AAPL))` which expires in 3 months?**

In order to use Margrabe formula from the lectures, we need to estimate the volatilities of the stocks and the correlation.

```{r}
AAPL <- as.numeric(AAPL); n <- length(AAPL)
AAPL.returns <- log(AAPL[2:n]/AAPL[1:(n-1)])
AAPL.returns <- AAPL.returns[-1] # the first value is NA


IBM <- as.numeric(IBM);  
IBM.returns <- log(IBM[2:n]/IBM[1:(n-1)]);
IBM.returns <- IBM.returns[-1] # the first value is NA

dt <- 1/252
AAPL.sigma = sqrt(var(AAPL.returns)/dt)
IBM.sigma= sqrt(var(IBM.returns)/dt)
```

Estimated `sigma` for the AAPL stock:
```{r}
AAPL.sigma
```

Estimated `sigma` for the IBM stock:
```{r}
IBM.sigma
```


```{r}
AAPL.mu <- mean(AAPL.returns)/dt
dw1 <- (AAPL.returns - AAPL.mu*dt)/AAPL.sigma

IBM.mu <- mean(IBM.returns)/dt
dw2 <- (IBM.returns - IBM.mu*dt)/IBM.sigma

rho <- cov(dw1,dw2)/dt
```

Estimated `rho`
```{r}
rho
```

Now we can define a function giving the result of Margrabe formula
```{r}
margrabe <- function(tau, S1, S2, sigma1, sigma2, rho) {
  sigma.tilde.2 <- sigma1^2 + sigma2^2 - 2*rho*sigma1*sigma2
  d1 <- (log(S1/S2) + 0.5*sigma.tilde.2*tau)/(sqrt(sigma.tilde.2 * tau))
  d2 <- d1 - sqrt(sigma.tilde.2 * tau)
  S1 * pnorm(d1) - S2 * pnorm(d2)
}
```

and apply it to our data 
```{r}
margrabe(0.25, IBM[n], AAPL[n], IBM.sigma, AAPL.sigma, rho)
```