```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

# Applying bootstrap 

The following code generates $\left(X_{i}, Y_{i}\right)$ pairs.

```{r}
library(MASS)
generate_pairs <- function(n) {
  # Generate n pairs of financial returns.
  muX <- 2
  muY <- -1
  CovMx <- matrix(c(1, -.25, -.25, 2), nrow = 2)
  data <- mvrnorm(n = 100, mu = c(muX,muY), Sigma = CovMx)
  return(data.frame('X' = data[, 1], 
                    'Y' = data[, 2]))
}
```

```{r}
fin_pairs <- generate_pairs( 100 ); # Generate 100 (X,Y) pairs.
head(fin_pairs)
```

We are interested in 
$$
\hat{\alpha}=\frac{\hat{\sigma}_{Y}^{2}-\hat{\sigma}_{X Y}}{\hat{\sigma}_{X}^{2}+\hat{\sigma}_{Y}^{2}-2 \hat{\sigma}_{X Y}} 
$$

```{r}
Sigmahat <- cov(fin_pairs) 
Sigmahat
sigma2hatXX <- Sigmahat[1,1]
sigma2hatYY <- Sigmahat[2,2]
sigmahatXY <- Sigmahat[1,2]
```

The $\hat{\alpha}$ is

```{r}
alphahat <- (sigma2hatYY - sigmahatXY)/(sigma2hatXX + sigma2hatYY -2*sigmahatXY)
alphahat
```

While the true value of alpha is

```{r}
sigma2XX <- 1
sigma2YY <- 2
sigmaXY <- -0.25
alpha_true <-(sigma2YY - sigmaXY)/(sigma2XX + sigma2YY -2*sigmaXY)
alpha_true
```


Now, again, we're going to resample with replacement from our data, and compute our statistic $\hat{\alpha}$ on each resample. The hope is that these resampled versions of the statistic will resemble the distribution of the statistic evaluated on the original data.

1. Create a function to compute alphahat from a given data set.

2. Resample the data $B=200$ times, evaluating $\hat{\alpha}$ on each resample. Then, we'll use those resampled values to estimate the variance.

3. Create the confidence interval at the estimate. 

```{r, echo = FALSE}
# https://bookdown.org/larget_jacob/data-modeling-methods/bootstrap.html
```

