### Calculate Simple Marginal Expected Shortfall
# Call some packages
library(xts)
library(PerformanceAnalytics)
library(tidyquant)
library(magrittr)
library(tidyverse)
library(dplyr)


#### Started from here####
# Import the Dataset and simulate data
# Notification: We have to set up data frame sastisfying 'Year' is the first column and 'Index' is the last column

t <- 'D:/Rcode/RPub/MES/Simple MES.csv' 
data <- read.csv(t, header = TRUE)
nrow <- nrow(data)
noise2 <- rnorm(nrow, 0, 10) %>% round(1)
noise3 <- rnorm(nrow, 0, 20) %>% round(1)
data$Bank_2 <- data$Bank_1 + noise2
data$Bank_3 <- data$Bank_1 + noise3
data <- data[,c(1, 2, 4, 5, 3)]


# write function to calculate MES
f_return <- function(x){
  log(x) - log(lag(x))
}

f_MES <- function(data){
  #Step 1: calculate return data frame
  ncol <- length(data)
  r_data <- data[, 2:ncol] %>% lapply(f_return) %>% as.data.frame()
  r_data <- data.frame(data[, 1], r_data)
  c_names <- colnames(data[, 2:ncol]) %>% paste0('r_', .)
  colnames(r_data) <- c('Year', c_names)
  #Step 2: Calculate MES
  r_data %>% 
    group_by(Year) %>% 
    filter(., r_Index < VaR(r_Index, p = 0.95, method = 'historical')[1]) %>% 
    summarise_all(mean) %>% ungroup()
}
f_MES(data)
## # A tibble: 17 x 5
##     Year r_Bank_1 r_Bank_2 r_Bank_3 r_Index
##    <int>    <dbl>    <dbl>    <dbl>   <dbl>
##  1  2000 -0.00672 -0.00728  0.0146  -0.0311
##  2  2001 -0.0167  -0.0205  -0.0189  -0.0450
##  3  2002 -0.0155  -0.0144  -0.0196  -0.0269
##  4  2003 -0.00672 -0.0170  -0.00638 -0.0229
##  5  2004 -0.00399 -0.00104 -0.0267  -0.0227
##  6  2005 -0.00773 -0.00753  0.0135  -0.0176
##  7  2006 -0.0181  -0.0250  -0.0348  -0.0233
##  8  2007 -0.0113  -0.00974 -0.0112  -0.0263
##  9  2008 -0.0414  -0.0464  -0.0463  -0.0758
## 10  2009 -0.0240  -0.0303  -0.0337  -0.0473
## 11  2010 -0.0212  -0.0217  -0.00680 -0.0311
## 12  2011 -0.0245  -0.0224  -0.0147  -0.0390
## 13  2012 -0.00842 -0.00601 -0.0133  -0.0282
## 14  2013 -0.0152  -0.0154  -0.00693 -0.0272
## 15  2014 -0.00676 -0.00884 -0.00303 -0.0195
## 16  2015 -0.0202  -0.0165  -0.0232  -0.0316
## 17  2016 -0.0207  -0.0261  -0.0345  -0.0334