---
title: "Howto: An Example with Data Preparation"
author: "Dr. Simon Müller"
date: "`r Sys.Date()`"
output:
  html_document:
    toc: true
    toc_float: true
    theme: readable
    highlight: tango
    css: kable.css
vignette: >
  %\VignetteIndexEntry{Howto: An Example with Data Preparation}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

# Overview

Based on the Dieselgate scandal we want to show you how you are able to fetch data in R, perform an Event Study, and do some basic plots with our R package. 

```{r, message=F, echo=T, eval=FALSE}
library(tidyquant)
library(dplyr)
library(readr)
```

# Data Preparation

We use the package tidyquant to fetch the automotive stock data from Yahoo Finance. As we cannot get the full volume size from this companies through Yahoo Finance API, we do not perform a volume Event Study in this vignette.

Let's define the window from which we want to fetch the data of the German auto companies.
```{r, eval=FALSE}
startDate <- "2014-05-01"
endDate <- "2015-12-31"
```

We focus us on the big five motor manufacturers in Germany, namely

- VW Group
    - VW
    - Audi
    - Porsche
- Daimler
- BMW

```{r, eval=FALSE}
# Firm Data
firmSymbols <- c("VOW.DE", "NSU.DE", "PAH3.DE", "BMW.DE", "DAI.DE")
firmNames <- c("VW preferred", "Audi", "Porsche Automobil Hld", "BMW", "Daimler")
firmSymbols %>% 
  tidyquant::tq_get(from = startDate, to = endDate) %>% 
  dplyr::mutate(date = format(date, "%d.%m.%Y")) -> firmData
knitr::kable(head(firmData), pad=0)
```

As reference market we choose the DAX.

```{r, eval=FALSE}
# Index Data
indexSymbol <- c("^GDAXI")
indexName <- c("DAX")
indexSymbol %>% 
  tidyquant::tq_get(from = startDate, to = endDate) %>% 
  dplyr::mutate(date = format(date, "%d.%m.%Y")) -> indexData
indexData$symbol <- "DAX"
knitr::kable(head(indexData), pad=0)
```

Now, after we have fetched all the data, we prepare the data files for the API call, as described in the introductionary vignette. We prepare in this step already the volume data for later purposes. 
```{r, eval=FALSE}
# Price files for firms and market
firmData %>% 
  dplyr::select(symbol, date, adjusted) %>% 
  readr::write_delim(path      = "02_firmDataPrice.csv", 
                     delim     = ";", 
                     col_names = F)

indexData %>% 
  dplyr::select(symbol, date, adjusted) %>% 
  readr::write_delim(path      = "03_marketDataPrice.csv", 
                     delim     = ";", 
                     col_names = F)

# Volume files for firms and market
firmData %>% 
  dplyr::select(symbol, date, volume) %>% 
  readr::write_delim(path      = "02_firmDataVolume.csv", 
                     delim     = ";", 
                     col_names = F)

indexData %>% 
  dplyr::select(symbol, date, volume) %>% 
  readr::write_delim(path      = "03_marketDataVolume.csv", 
                     delim     = ";", 
                     col_names = F)
```

Finally, we have to prepare the request file. The parameters for this Event Study are:

- Estimation window: 250
- Event window: -10 to 10
- Event date: 18.09.2015

Details of the format can be found in the introductionary vignette.

```{r, eval=FALSE}
group <- c(rep("VW Group", 3), rep("Other", 2))
request <- cbind(c(1:5), firmSymbols, rep(indexName, 5), rep("18.09.2015", 5), group, rep(-10, 5), rep(10, 5), rep(-11, 5), rep(250, 5))
request %>% 
  as.data.frame() %>% 
  readr::write_delim("01_requestFile.csv", delim = ";", col_names = F)
```


# Perform Event Studies: Abnormal Return, Volume, and Volatility

After the preparation steps, we are now able to start the calculations. We use in all type of Event Studies the GARCH(1, 1) model. Please consider in your Event Studies that fitting this model is computationally expensive and delayed response from the API should be expected. 

## Abnormal Return Event Study

```{r, message=F, eval=F}
key <- "573e58c665fcc08cc6e5a660beaad0cb"

library(EventStudy)
est <- EventStudyAPI$new()
est$authentication(apiKey = key)

# get & set parameters for abnormal return Event Study
# we use a garch model and csv as return
# Attention: fitting a GARCH(1, 1) model is compute intensive
esaParams <- EventStudy::ARCApplicationInput$new()
esaParams$setResultFileType("csv")
esaParams$setBenchmarkModel("garch")

dataFiles <- c("request_file" = "01_requestFile.csv",
               "firm_data"    = "02_firmDataPrice.csv",
               "market_data"  = "03_marketDataPrice.csv")

# check data files, you can do it also in our R6 class
EventStudy::checkFiles(dataFiles)

# now let us perform the Event Study
arEventStudy <- est$performEventStudy(estParams     = esaParams, 
                                      dataFiles     = dataFiles, 
                                      downloadFiles = T)
```

Now, you can use the downloaded CSV (or your preferred data format) files in your analysis. During the creation of the `arEventStudy` object we merge information from the request file, and the result files.

```{r, eval=F}
knitr::kable(head(arEventStudy$arResults))
```


The averaged abnormal return (aar) `data.frame` has the following shape:

```{r, eval=F}
knitr::kable(head(arEventStudy$aarResults))
```

You can find the statistic naming in `arEventStudy$aarStatistics`.


## Abnormal Volatility Event Study

```{r, message=F, eval=F}
est <- EventStudyAPI$new()
est$authentication(apiKey = key)

# get & set parameters for abnormal return Event Study
esaParams <- EventStudy::AVyCApplicationInput$new()
esaParams$setResultFileType("csv")
 
avycEventStudy <- est$performEventStudy(estParams    = esaParams, 
                                       dataFiles     = dataFiles,
                                       downloadFiles = T)
```

The prepared `data.frames` in `avycEventStudy` have a similar shape as for the abnormal return Event Study. 

## Abnormal Volume Event Study

This will be added in a later stage.

```{r, eval=F}
# est <- EventStudyAPI$new()
# est$authentication(apiKey = key)
# 
# # get & set parameters for abnormal return Event Study
# esaParams <- EventStudy::AVCApplicationInput$new()
# esaParams$setResultFileType("csv")
# 
# avEventStudy <- est$performEventStudy(estParams = esaParams,
#                       dataFiles = c("request_file" = "01_requestFile.csv",
#                                     "firm_data"    = "02_firmDataVolume.csv",
#                                     "market_data"  = "03_marketDataVolume.csv"))
```

