listOfPackages <- c("esquisse", "ggplot2", "dplyr")
for (i in listOfPackages) {
if (!i %in% installed.packages()) {
install.packages(i, dependencies = TRUE)
}
require(i, character.only = TRUE)
}
load(url("https://cursoronline.usal.es/Quotes.RData"))Date1 <- merge(
x = portfolio_series$green_portfolio,
y = portfolio_series$neutral_portfolio,
by = "Dates", all = FALSE
)
Date1 <- merge(
x = Date1,
y = portfolio_series$brown_portfolio,
by = "Dates", all = FALSE
)
names(Date1) <- c("Dates", "Green", "Neutral", "Brown")financial_quotes$Dates <- as.Date(financial_quotes$Dates)
MatrizCotizacion <- merge(
x = financial_quotes,
y = Date1,
by = "Dates", all = FALSE
)
# Matriz de rendimientos
MatrizR <- log(MatrizCotizacion[2:dim(MatrizCotizacion)[1], -1]) -
log(MatrizCotizacion[1:(dim(MatrizCotizacion)[1] - 1), -1])
# Simulamos rendimientos
Msim <- MatrizR[sample(dim(MatrizR)[1], 100000, replace = TRUE), ]
# Umbrales según tipo de cartera
thresholdGreen <- quantile(MatrizR$Green, c(0.2, 0.4, 0.6, 0.8), na.rm = TRUE)
thresholdBrown <- quantile(MatrizR$Brown, c(0.2, 0.4, 0.6, 0.8), na.rm = TRUE)
thresholdNeutral <- quantile(MatrizR$Brown, c(0.4, 0.6), na.rm = TRUE)# Transicion desordenada
ID_disorderly <- (thresholdGreen[4] < Msim$Green) &
(thresholdBrown[1] > Msim$Brown)
# No transicion
ID_hothouse <- (thresholdGreen[1] > Msim$Green) &
(thresholdBrown[4] < Msim$Brown)
# Transicion ordenada
ID_orderly <- (thresholdGreen[2] < Msim$Green) &
(thresholdGreen[3] > Msim$Green) & (thresholdBrown[3] > Msim$Brown) &
(thresholdBrown[2] > Msim$Brown) & (thresholdNeutral[2] > Msim$Neutral) &
(thresholdNeutral[1] > Msim$Neutral)returns_disorderly <- apply(
Msim[ID_disorderly, -c((dim(Msim)[2] - 2):dim(Msim)[2])],
2, mean,
na.rm = TRUE
) * 250
returns_orderly <- apply(
Msim[ID_orderly, -c((dim(Msim)[2] - 2):dim(Msim)[2])],
2, mean,
na.rm = TRUE
) * 250
returns_hothouse <- apply(
Msim[ID_hothouse, -c((dim(Msim)[2] - 2):dim(Msim)[2])],
2, mean,
na.rm = TRUE
) * 250
Symbol <- names(Msim[, -c((dim(Msim)[2] - 2):dim(Msim)[2])])
Scenarios <- data.frame(
returns_disorderly,
returns_orderly, returns_hothouse, Symbol
)Finalmente generamos algunas figuras para ver cual es el resultado para las entidades con mas problemas en cada escenario, el resultado por sector y el resultado por pais
load(url("https://cursoronline.usal.es/Data_features.Rdata"))
ScenarioGraphInput <- merge(
x = Scenarios,
y = df_financial_EU,
by = "Symbol", all = FALSE
)
# Este comando permite explorar interactivamente los datos visualizándolos con el paquete ggplot2
# esquisse::esquisser()ScenarioGraphInput %>%
filter(returns_disorderly >= -24L & returns_disorderly <= -11L & !is.na(returns_disorderly)) %>%
filter(!is.na(returns_hothouse)) %>%
ggplot() +
aes(x = Name, weight = returns_disorderly) +
geom_bar(fill = "#112446") +
labs(
x = "Perdidas",
y = "Empresas financieras",
caption = "Escenario de transición desordenada"
) +
coord_flip() +
theme_minimal()ScenarioGraphInput %>%
filter(returns_orderly >= -5.2 & returns_orderly <= -1.8 & !is.na(returns_orderly)) %>%
ggplot() +
aes(x = Name, weight = returns_orderly) +
geom_bar(fill = "#112446") +
labs(
x = "Perdidas",
y = "Empresas financieras",
caption = "Escenario de transición ordenada"
) +
coord_flip() +
theme_minimal()ScenarioGraphInput %>%
filter(returns_hothouse >= -4.8 & returns_hothouse <= -2.2 & !is.na(returns_hothouse)) %>%
ggplot() +
aes(x = Name, weight = returns_hothouse) +
geom_bar(fill = "#112446") +
labs(
x = "Perdidas",
y = "Empresas financieras",
caption = "Escenario de no transicion"
) +
coord_flip() +
theme_minimal()ScenarioGraphInput %>%
filter(!is.na(returns_disorderly)) %>%
ggplot() +
aes(x = returns_disorderly, y = Country) +
geom_boxplot(fill = "#112446") +
labs(
x = "Perdidas",
y = "Paises",
caption = "Escenario de transicion desordenada"
) +
theme_minimal()ScenarioGraphInput %>%
filter(!is.na(returns_orderly)) %>%
ggplot() +
aes(x = returns_orderly, y = Country) +
geom_boxplot(fill = "#112446") +
labs(
x = "Perdidas",
y = "Paises",
caption = "Escenario de transicion ordenada"
) +
theme_minimal()ScenarioGraphInput %>%
filter(!is.na(returns_hothouse)) %>%
ggplot() +
aes(x = returns_hothouse, y = Country) +
geom_boxplot(fill = "#112446") +
labs(
x = "Perdidas",
y = "Paises",
caption = "Escenario de no transicion"
) +
theme_minimal()ggplot(ScenarioGraphInput) +
aes(x = returns_disorderly, fill = Industry) +
labs(
x = "Rendimientos esperados",
y = "Frecuencia",
caption = "Escenario de transicion desordenada"
) +
geom_histogram(bins = 30L) +
scale_fill_hue(direction = 1) +
theme_minimal()ggplot(ScenarioGraphInput) +
aes(x = returns_orderly, fill = Industry) +
labs(
x = "Rendimientos esperados",
y = "Frecuencia",
caption = "Escenario de transicion ordenada"
) +
geom_histogram(bins = 30L) +
scale_fill_hue(direction = 1) +
theme_minimal()ggplot(ScenarioGraphInput) +
aes(x = returns_hothouse, fill = Industry) +
labs(
x = "Rendimientos esperados",
y = "Frecuencia",
caption = "Escenario de no transicion"
) +
geom_histogram(bins = 30L) +
scale_fill_hue(direction = 1) +
theme_minimal()Script usado para la obtención de los “.RData” usados en este proyecto (se deben actualizar los enlaces para el correcto funcionamiento)
listOfPackages <- c(
"curl", "XML", "rvest", "quantmod", "xts", "rjson",
"data.table", "zoo", "lubridate", "utils"
)
for (i in listOfPackages) {
if (!i %in% installed.packages()) {
install.packages(i, dependencies = TRUE)
}
require(i, character.only = TRUE)
}
# Descarga tickets bolsa por bolsa
# AUSTRIA
N <- 6926
for (i in seq.int(0, N, 100)) {
txt_address <- paste0(
"https://finance.yahoo.com/screener/unsaved/8125691c-02c1-439a-adb6-5e541dbf3d96?offset=",
i, "&count=100"
)
con <- curl(txt_address)
address_web <- XML::readHTMLTable(
readLines(
con,
warn = FALSE
)
)
activos_temp <- address_web[[1]]$Symbol
close(con)
if (i == 0) {
quotes <- data.frame(Symbol = activos_temp)
} else {
quotes[c(nrow(quotes) + 1:length(activos_temp)), ] <- activos_temp
}
rm(activos_temp, address_web)
# imprimir el punto en el que nos encontramos
print(paste0("Completed ", sprintf("%0.2f%%", i / N * 100), " - Austria"))
}
print(paste0("Completed ", sprintf("%0.2f%%", N / N * 100), " - Austria"))
# BELGICA
N <- 169
for (i in seq.int(0, N, 100)) {
txt_address <- paste0(
"https://finance.yahoo.com/screener/unsaved/8bc221a3-8d13-4902-8e89-207227b218fc?offset=",
i, "&count=100"
)
con <- curl(txt_address)
address_web <- XML::readHTMLTable(
readLines(
con,
warn = FALSE
)
)
activos_temp <- address_web[[1]]$Symbol
close(con)
quotes[c(nrow(quotes) + 1:length(activos_temp)), ] <- activos_temp
rm(activos_temp, address_web)
# imprimir el punto en el que nos encontramos
print(paste0("Completed ", sprintf("%0.2f%%", i / N * 100), " - Belgium"))
}
print(paste0("Completed ", sprintf("%0.2f%%", N / N * 100), " - Belgium"))
# GERMANY
N <- 57075
for (i in seq.int(0, N, 100)) {
txt_address <- paste0(
"https://finance.yahoo.com/screener/unsaved/65705f5f-0ccf-46a0-b2c4-e8b5a0f808e1?offset=",
i, "&count=100"
)
con <- curl(txt_address)
address_web <- XML::readHTMLTable(
readLines(
con,
warn = FALSE
)
)
if (length(address_web) == 0) {
close(con)
print(paste0("Completed ", sprintf("%0.2f%%", N / N * 100), " - Germany"))
} else {
activos_temp <- address_web[[1]]$Symbol
close(con)
quotes[c(nrow(quotes) + 1:length(activos_temp)), ] <- activos_temp
rm(activos_temp, address_web)
# imprimir el punto en el que nos encontramos
print(paste0("Completed ", sprintf("%0.2f%%", i / N * 100), " - Germany"))
}
}
print(paste0("Completed ", sprintf("%0.2f%%", N / N * 100), " - Germany"))
# ESTONIA
N <- 21
for (i in seq.int(0, N, 100)) {
txt_address <- paste0(
"https://finance.yahoo.com/screener/unsaved/c5959c50-0097-4a05-ad3d-af5c72f44a75?offset=",
i, "&count=100"
)
con <- curl(txt_address)
address_web <- XML::readHTMLTable(
readLines(
con,
warn = FALSE
)
)
activos_temp <- address_web[[1]]$Symbol
close(con)
quotes[c(nrow(quotes) + 1:length(activos_temp)), ] <- activos_temp
rm(activos_temp, address_web)
# imprimir el punto en el que nos encontramos
print(paste0("Completed ", sprintf("%0.2f%%", i / N * 100), " - Estonia"))
}
print(paste0("Completed ", sprintf("%0.2f%%", N / N * 100), " - Estonia"))
# ESPAÑA
N <- 196
for (i in seq.int(0, N, 100)) {
txt_address <- paste0(
"https://finance.yahoo.com/screener/unsaved/7560ed39-ca2c-4093-a4c2-87e77d5f7a2e?offset=",
i, "&count=100"
)
con <- curl(txt_address)
address_web <- XML::readHTMLTable(
readLines(
con,
warn = FALSE
)
)
activos_temp <- address_web[[1]]$Symbol
close(con)
quotes[c(nrow(quotes) + 1:length(activos_temp)), ] <- activos_temp
rm(activos_temp, address_web)
# imprimir el punto en el que nos encontramos
print(paste0("Completed ", sprintf("%0.2f%%", i / N * 100), " - Spain"))
}
print(paste0("Completed ", sprintf("%0.2f%%", N / N * 100), " - Spain"))
# FINLANDIA
N <- 201
for (i in seq.int(0, N, 100)) {
txt_address <- paste0(
"https://finance.yahoo.com/screener/unsaved/11deffa9-b7d8-4ac9-84a9-183a3797aa2a?offset=",
i, "&count=100"
)
con <- curl(txt_address)
address_web <- XML::readHTMLTable(
readLines(
con,
warn = FALSE
)
)
activos_temp <- address_web[[1]]$Symbol
close(con)
quotes[c(nrow(quotes) + 1:length(activos_temp)), ] <- activos_temp
rm(activos_temp, address_web)
# imprimir el punto en el que nos encontramos
print(paste0("Completed ", sprintf("%0.2f%%", i / N * 100), " - Finland"))
}
print(paste0("Completed ", sprintf("%0.2f%%", N / N * 100), " - Finland"))
# FRANCIA
N <- 8236
for (i in seq.int(0, N, 100)) {
txt_address <- paste0(
"https://finance.yahoo.com/screener/unsaved/ecc9f688-14e7-42eb-b95a-500156a43627?offset=",
i, "&count=100"
)
con <- curl(txt_address)
address_web <- XML::readHTMLTable(
readLines(
con,
warn = FALSE
)
)
activos_temp <- address_web[[1]]$Symbol
close(con)
quotes[c(nrow(quotes) + 1:length(activos_temp)), ] <- activos_temp
rm(activos_temp, address_web)
# imprimir el punto en el que nos encontramos
print(paste0("Completed ", sprintf("%0.2f%%", i / N * 100), " - France"))
}
print(paste0("Completed ", sprintf("%0.2f%%", N / N * 100), " - France"))
# GRECIA
N <- 155
for (i in seq.int(0, N, 100)) {
txt_address <- paste0(
"https://finance.yahoo.com/screener/unsaved/dbbb94a8-f088-46af-9a44-714872d7fe31?offset=",
i, "&count=100"
)
con <- curl(txt_address)
address_web <- XML::readHTMLTable(
readLines(
con,
warn = FALSE
)
)
activos_temp <- address_web[[1]]$Symbol
close(con)
quotes[c(nrow(quotes) + 1:length(activos_temp)), ] <- activos_temp
rm(activos_temp, address_web)
# imprimir el punto en el que nos encontramos
print(paste0("Completed ", sprintf("%0.2f%%", i / N * 100), " - Greece"))
}
print(paste0("Completed ", sprintf("%0.2f%%", N / N * 100), " - Greece"))
# IRLANDA
N <- 34
for (i in seq.int(0, N, 100)) {
txt_address <- paste0(
"https://finance.yahoo.com/screener/unsaved/ffdd1025-5f72-417f-925c-498173ee61df?offset=",
i, "&count=100"
)
con <- curl(txt_address)
address_web <- XML::readHTMLTable(
readLines(
con,
warn = FALSE
)
)
activos_temp <- address_web[[1]]$Symbol
close(con)
quotes[c(nrow(quotes) + 1:length(activos_temp)), ] <- activos_temp
rm(activos_temp, address_web)
# imprimir el punto en el que nos encontramos
print(paste0("Completed ", sprintf("%0.2f%%", i / N * 100), " - Ireland"))
}
print(paste0("Completed ", sprintf("%0.2f%%", N / N * 100), " - Ireland"))
# ITALIA
N <- 1877
for (i in seq.int(0, N, 100)) {
txt_address <- paste0(
"https://finance.yahoo.com/screener/unsaved/413ac38f-5de2-45e6-836d-df919f1bd248?offset=",
i, "&count=100"
)
con <- curl(txt_address)
address_web <- XML::readHTMLTable(
readLines(
con,
warn = FALSE
)
)
activos_temp <- address_web[[1]]$Symbol
close(con)
quotes[c(nrow(quotes) + 1:length(activos_temp)), ] <- activos_temp
rm(activos_temp, address_web)
# imprimir el punto en el que nos encontramos
print(paste0("Completed ", sprintf("%0.2f%%", i / N * 100), " - Italy"))
}
print(paste0("Completed ", sprintf("%0.2f%%", N / N * 100), " - Italy"))
# LITUANIA
N <- 25
for (i in seq.int(0, N, 100)) {
txt_address <- paste0(
"https://finance.yahoo.com/screener/unsaved/c62af9c2-f2fd-418a-afc1-bf8313639cb8?offset=",
i, "&count=100"
)
con <- curl(txt_address)
address_web <- XML::readHTMLTable(
readLines(
con,
warn = FALSE
)
)
activos_temp <- address_web[[1]]$Symbol
close(con)
quotes[c(nrow(quotes) + 1:length(activos_temp)), ] <- activos_temp
rm(activos_temp, address_web)
# imprimir el punto en el que nos encontramos
print(paste0("Completed ", sprintf("%0.2f%%", i / N * 100), " - Lithuania"))
}
print(paste0("Completed ", sprintf("%0.2f%%", N / N * 100), " - Lithuania"))
# LETONIA
N <- 25
for (i in seq.int(0, N, 100)) {
txt_address <- paste0(
"https://finance.yahoo.com/screener/unsaved/7639411a-81fc-4765-adab-cf968ce86829?offset=",
i, "&count=100"
)
con <- curl(txt_address)
address_web <- XML::readHTMLTable(
readLines(
con,
warn = FALSE
)
)
activos_temp <- address_web[[1]]$Symbol
close(con)
quotes[c(nrow(quotes) + 1:length(activos_temp)), ] <- activos_temp
rm(activos_temp, address_web)
# imprimir el punto en el que nos encontramos
print(paste0("Completed ", sprintf("%0.2f%%", i / N * 100), " - Latvia"))
}
print(paste0("Completed ", sprintf("%0.2f%%", N / N * 100), " - Latvia"))
# PAISES BAJOS
N <- 301
for (i in seq.int(0, N, 100)) {
txt_address <- paste0(
"https://finance.yahoo.com/screener/unsaved/9624c782-4cec-45c5-b657-08e303386123?offset=",
i, "&count=100"
)
con <- curl(txt_address)
address_web <- XML::readHTMLTable(
readLines(
con,
warn = FALSE
)
)
activos_temp <- address_web[[1]]$Symbol
close(con)
quotes[c(nrow(quotes) + 1:length(activos_temp)), ] <- activos_temp
rm(activos_temp, address_web)
# imprimir el punto en el que nos encontramos
print(paste0("Completed ", sprintf("%0.2f%%", i / N * 100), " - Netherlands"))
}
print(paste0("Completed ", sprintf("%0.2f%%", N / N * 100), " - Netherlands"))
# PORTUGAL
N <- 67
for (i in seq.int(0, N, 100)) {
txt_address <- paste0(
"https://finance.yahoo.com/screener/unsaved/e4eb3254-bcd3-4abc-b6e8-5b3fda0415ca?offset=",
i, "&count=100"
)
con <- curl(txt_address)
address_web <- XML::readHTMLTable(
readLines(
con,
warn = FALSE
)
)
activos_temp <- address_web[[1]]$Symbol
close(con)
quotes[c(nrow(quotes) + 1:length(activos_temp)), ] <- activos_temp
rm(activos_temp, address_web)
# imprimir el punto en el que nos encontramos
print(paste0("Completed ", sprintf("%0.2f%%", i / N * 100), " - Portugal"))
}
print(paste0("Completed ", sprintf("%0.2f%%", N / N * 100), " - Portugal"))
# Guardamos el dataframe con los simbolos de las empresas cotizando en las bolsas de la euro zona
save(quotes, file = "quotes.Rdata")
getProfile <- function(idx) {
# cambiar user_agent e introducer retrasos ayuda a evitar errore 503
uagent <- c(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36"
)
url <- paste0("https://finance.yahoo.com/quote/", idx, "/profile?p=", idx)
dt <- read_html(url, user_agent = uagent[sample(5, 1)])
Sys.sleep(sample(10, 1) * 0.1)
# Comprobamos que el sector y la industrial son campos que se pueden exportar
trym <- tryCatch(dt %>% html_nodes(xpath = '//*[@id="Col1-0-Profile-Proxy"]/section/div[1]/div/div/p[2]') %>%
.[[1]] %>% html_children(),
error = function(e) {
TRUE
}
)
if (is.logical(trym) == FALSE) {
if (length(html_text(trym[2])) != 0) {
const <- dt %>%
html_nodes(xpath = '//*[@id="Col1-0-Profile-Proxy"]/section/div[1]/div/div/p[2]') %>%
.[[1]] %>%
html_children()
out_address <- strsplit(html_text2(dt %>%
html_nodes(xpath = '//*[@id="Col1-0-Profile-Proxy"]/section/div[1]/div/div/p[1]') %>%
.[1]), "\n")
id_address <- html_text2(dt %>%
html_nodes(xpath = '//*[@id="Col1-0-Profile-Proxy"]/section/div[1]/div/div/p[1]') %>%
.[1] %>% html_children())
id_country <-
if (length(which(!id_address == "")) == 0) {
max(which(!out_address[[1]] == ""))
} else {
if (length(which(out_address[[1]] == "")) == 0) {
10
}
if (min(which(out_address[[1]] == "")) == 1) {
10
}
if (which(out_address[[1]] == "") - 1) {
min(which(!id_address == "")) - 1
}
}
Profile <- data.frame(
Name = html_text(dt %>% html_nodes(xpath = '//*[@id="Col1-0-Profile-Proxy"]/section/div[1]/div/h3')),
Country = out_address[[1]][id_country],
Sector = html_text(const[2]),
Industry = html_text(const[5])
)
} else {
Profile <- data.frame(
Name = "NA",
Country = "NA",
Sector = "NA",
Industry = "NA"
)
}
} else {
Profile <- data.frame(
Name = "NA",
Country = "NA",
Sector = "NA",
Industry = "NA"
)
}
Profile
}
# Añadimos para todas las empresas el sector y la industria cuando se encuentre disponible
# df<-data.frame(Symbol=character(),Name=character(),Country=character(),Sector=character(),Industry=character())
for (j in c(1:dim(quotes)[1])) {
temp_profile <- getProfile(quotes$Symbol[j])
df[j, ] <- "NA"
df$Symbol[j] <- quotes$Symbol[j]
df$Name[j] <- temp_profile$Name
df$Country[j] <- temp_profile$Country
df$Sector[j] <- temp_profile$Sector
df$Industry[j] <- temp_profile$Industry
rm(temp_profile)
print(paste0("Completed profile - ", sprintf("%0.4f%%", j / dim(quotes)[1] * 100)))
}
# Guardamos las caracteristicas de los activos
save(df, file = "profile.Rdata")
# Eliminamos aquellas cotizaciones para las cuales no tenemos informacion
df_filter <- df[(df$Name != "NA") & (df$Sector != ""), ]
temp_names <- unique(df_filter$Name)
# Eliminamos duplicados en los nombres de las empresas, pero nos quedamos con la cotizacion que ofrezca la serie historica mas larga
# Descarga todos, compara y da como output el ticker del que sea mas largo, que correspondera con la bolsa principal
getQuote <- function(idx) {
# Importa datos de Yahoo! Finance
len_date <- c()
for (k in c(1:length(idx))) {
options("getSymbols.warning4.0" = FALSE)
# Comprobamos si los datos historicos estan disponibles
trym <- tryCatch(getSymbols(Symbols = idx[k], env = NULL, warnings = FALSE), error = function(e) TRUE)
if (is.logical(trym)) {
len_date[k] <- 0
} else {
temp_quote <- getSymbols(Symbols = idx[k], env = NULL, warnings = FALSE)
Dates <- index(temp_quote)
len_date[k] <- length(Dates)
}
}
# Identificamos la serie mas larga
id_idx <- which(max(len_date) == len_date)
if (length(id_idx) > 1) {
output <- idx[id_idx[1]]
} else {
output <- idx[id_idx]
}
output
}
# Aplicamos el codigo para aquellas empresas que cotizan en multiples bolsas
list_q <- c()
for (i in c(1:length(temp_names))) {
temp_codes <- df_filter[df_filter$Name == temp_names[i], "Symbol"]
# En caso de que cotice en multiples bolsas
if (length(temp_codes) > 1) {
temp_q <- getQuote(temp_codes)
} else {
temp_q <- temp_codes
}
list_q <- c(list_q, temp_q)
rm(temp_q)
print(paste0("Completed firm list - ", sprintf("%0.4f%%", i / length(temp_names) * 100)))
}
df_filter_unique <- df_filter[(df_filter$Symbol %in% list_q), ]
# Filtro por euro area (EA) y Union Europea (EU)
EU_countries <- c(
"Austria", "Belgium", "Bulgaria", "Croatia", "Cyprus",
"Czech Republic", "Denmark", "Estonia", "Finland", "France", "Germany",
"Greece", "Hungary", "Ireland", "Italy", "Latvia", "Lithuania", "Luxembourg",
"Malta", "Netherlands", "Poland", "Portugal", "Romania", "Slovakia",
"Slovenia", "Spain", "Sweden"
)
EA_countries <- c(
"Austria", "Belgium", "Cyprus", "Estonia",
"Finland", "France", "Germany", "Greece", "Ireland", "Italy",
"Latvia", "Lithuania", "Luxembourg", "Malta", "Netherlands",
"Portugal", "Slovakia", "Slovenia", "Spain"
)
# Nombres de las empresas europeas financieras y sus tickers. Anadimos una columna indicando si estan dentro de la EA o no.
df_filter_unique$EU <- (df_filter_unique$Country %in% EU_countries)
df_filter_unique$EA <- (df_filter_unique$Country %in% EA_countries)
df_financial_EU <- df_filter_unique[(df_filter_unique$EU == TRUE) &
((df_filter_unique$Sector == "Financial Services") |
(df_filter_unique$Sector == "Financial")), ]
rownames(df_financial_EU) <- NULL
df_portfolio <- df_filter_unique[!((df_filter_unique$Sector == "Financial Services") | (df_filter_unique$Sector == "Financial")), ]
rownames(df_portfolio) <- NULL
# Guardamos los datos
save(df_financial_EU, df_portfolio, file = "Data_features.Rdata")
# Esta funcion nos da el rating ambiental de cada empresa cotizada, que emplearemos para formar las carteras
getDat_Escore <- function(idx) {
uagent <- c(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36"
)
# scrape_url <-url(paste0("https://query2.finance.yahoo.com/v1/finance/esgChart?symbol=",idx),headers=c("User-Agent"=uagent[sample(5,1)]))
scrape_url <- httr::GET(paste0("https://query2.finance.yahoo.com/v1/finance/esgChart?symbol=", idx), httr::user_agent(uagent[sample(5, 1)]))
# trym<-tryCatch(readLines(con = scrape_url, warn=FALSE))
# flat_html <- readLines(scrape_url, warn=FALSE)#,user_agent = uagent[sample(5,1)])
flat_html <- httr::content(scrape_url, "text")
# write(flat_html, "output.json")
# result <- fromJSON(file = "output.json")
Sys.sleep(sample(30, 1) * 0.1)
result <- fromJSON(flat_html)
# close(scrape_url, warn=FALSE)
Dates <- as.Date(as.POSIXlt(result$esgChart$result[[1]]$symbolSeries$timestamp, origin = "1970-01-01 00:00.00 UTC"))
#
if (class(result$esgChart$result[[1]]$symbolSeries$environmentScore) == "list") {
E_score <- transpose(result$esgChart$result[[1]]$symbolSeries$environmentScore)
} else if (class(result$esgChart$result[[1]]$symbolSeries$environmentScore) == "NULL") {
E_score <- NA
} else {
E_score <- transpose(list(result$esgChart$result[[1]]$symbolSeries$environmentScore))
}
E_score <- as.numeric(na.locf(zoo(as.numeric(unlist(E_score))), na.rm = FALSE))
if (length(Dates) == 0) {
Dates <- NA
}
output <- data.frame(Dates, E_score)
output
}
# Esta funcion obtiene el rating ambiental siguiendo la funcion creada anteriormente
df_timeseries <- list()
for (i in c(1:length(df_portfolio$Symbol))) {
temp_data <- getDat_Escore(df_portfolio$Symbol[i])
if (i == 1) {
df_timeseries <- list(temp_data)
} else {
df_timeseries[[i]] <- temp_data
}
rm(temp_data)
print(paste0("Completed download portfolio - ", sprintf("%0.4f%%", i / length(df_portfolio$Symbol) * 100)))
}
names(df_timeseries) <- df_portfolio$Symbol
# save(df_timeseries,file="ESG_portfolio.RData")
# Un E score mas bajo significa menos expuesto y mas alto significa mas expuesto
# Por un lado se busca tener coherencia con Ojea-Ferreiro et al. (2022)
# y por otro el cambio en la metodologia que expone en Rzeznik et al. (2021)
# Fuente: https://deliverypdf.ssrn.com/delivery.php?ID=284123064090005000111084113096098065040086057015091007085093118078112067011004090069106114044017059048002100027120115096021083060078047087052021067004084127106119092020060079029086070120085001119100064010118074014122127096108090082090093067080024031125&EXT=pdf&INDEX=TRUE
# https://joint-research-centre.ec.europa.eu/publications/impact-climate-transition-risks-financial-stability-systemic-risk-approach_en
# Realizamos ese cambio e identificamos las empresas para las que no tenemos E score
delete_firm <- c()
for (i in c(1:length(df_timeseries))) {
if (is.na(df_timeseries[[i]]$E_score)) {
delete_firm <- c(delete_firm, i)
} else {
if ((min(year(df_timeseries[[i]]$Dates)) < 2019) & (max(year(df_timeseries[[i]]$Dates)) > 2020)) {
id_change <- which(max(abs(diff(df_timeseries[[i]]$E_score))) == abs(diff(df_timeseries[[i]]$E_score))) + 1
df_timeseries[[i]]$E_score[df_timeseries[[i]]$Dates < df_timeseries[[i]]$Dates[[id_change]]] <- 100 - df_timeseries[[i]]$E_score[df_timeseries[[i]]$Dates < df_timeseries[[i]]$Dates[[id_change]]]
}
}
}
# Eliminamos las empresas para las que no tenemos datos
df_timeseries_clean <- df_timeseries[-delete_firm]
# Obtenemos las fechas en las que rebalanceamos las carteras
df_date <- do.call(rbind, df_timeseries_clean)
Dates_portfolio <- unique(df_date$Dates)
rm(df_date)
# Cada mes identificar los percentiles 20 y 80 en seccion cruzada que definen las carteras verde y marron
# y clasificar a las firmas segun su puntuacion
#
df_tranch_portfolio <- list()
for (j in c(1:length(Dates_portfolio))) {
cross_E_score <- unlist(lapply(df_timeseries_clean, function(x) {
if (any(x$Dates == Dates_portfolio[j])) {
x$E_score[x$Dates == Dates_portfolio[j]]
}
}))
threshold_portfolio <- quantile(cross_E_score, c(0.2, 0.8))
if (j == 1) {
df_tranch_portfolio[[j]] <- list(
green_portfolio = names(cross_E_score[cross_E_score < threshold_portfolio[[1]]]),
neutral_portfolio = names(cross_E_score[(cross_E_score > threshold_portfolio[[1]]) & (cross_E_score < threshold_portfolio[[2]])]),
brown_portfolio = names(cross_E_score[cross_E_score > threshold_portfolio[[2]]])
)
} else {
df_tranch_portfolio[[j]] <- list(
green_portfolio = names(cross_E_score[cross_E_score < threshold_portfolio[[1]]]),
neutral_portfolio = names(cross_E_score[(cross_E_score > threshold_portfolio[[1]]) & (cross_E_score < threshold_portfolio[[2]])]),
brown_portfolio = names(cross_E_score[cross_E_score > threshold_portfolio[[2]]])
)
}
print(paste0("Classifying assets into portfolios - ", sprintf("%0.4f%%", j / length(Dates_portfolio) * 100)))
rm(cross_E_score, threshold_portfolio)
}
names(df_tranch_portfolio) <- Dates_portfolio
# Guardamos los datos
save(df_financial_EU, df_tranch_portfolio, file = "Portfolio_base.RData")
# Descargamos los datos de cotizacion de las entidades europeas
Financial_firms <- c(df_financial_EU$Symbol)
oldagent <- options("HTTPUserAgent")
uagent <- c(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36"
)
for (i in c(1:length(Financial_firms))) {
temp_uagent <- uagent[sample(5, 1)]
scrape_url <- httr::GET(
paste0(
"https://query1.finance.yahoo.com/v7/finance/download/",
Financial_firms[i], "?period1=", as.numeric(as.POSIXct("2014-08-01", format = "%Y-%m-%d")),
"&period2=", as.numeric(as.POSIXct(Sys.Date(), format = "%Y-%m-%d")),
"&interval=1d&events=history&includeAdjustedClose=true"
),
httr::user_agent(temp_uagent)
)
options(HTTPUserAgent = temp_uagent)
flat_html <- read.csv(file = scrape_url$url, sep = ",")
temp_q <- data.frame(flat_html$Date, as.numeric(flat_html$Close))
colnames(temp_q) <- c("Dates", Financial_firms[i])
Sys.sleep(sample(10, 1) * 0.1)
if (i == 1) {
financial_quotes <- temp_q
} else {
financial_quotes <- merge(
x = financial_quotes, y = temp_q,
by = "Dates", all.x = TRUE
)
}
rm(scrape_url, flat_html, temp_q)
print(paste0(
"Downloading historical data from financial firms - ",
sprintf("%0.4f%%", i / length(Financial_firms) * 100)
))
}
options(HTTPUserAgent = oldagent)
datesportfolio <- names(df_tranch_portfolio)
namesSubportfolios <- names(df_tranch_portfolio[[1]])
## Ceamos el portfolio...
portfolio_series <- c(namesSubportfolios, list())
names(portfolio_series) <- namesSubportfolios
loc <- Sys.getlocale("LC_TIME")
Sys.setlocale("LC_TIME", "en_GB.UTF-8")
suppressWarnings()
for (d in c(1:length(datesportfolio))) {
for (s in c(1:length(namesSubportfolios))) {
if (d < length(datesportfolio)) {
cc <- 0
for (k in c(1:length(df_tranch_portfolio[[d]][[s]]))) {
temp_uagent <- uagent[sample(5, 1)]
txt_address <- paste0(
"https://query1.finance.yahoo.com/v7/finance/download/",
df_tranch_portfolio[[d]][[s]][k], "?period1=",
as.numeric(as.POSIXct(as.Date(format(as.Date(datesportfolio[d]) - 30, "%Y-%m-01")),
format = "%Y-%m-%d"
)), "&period2=", as.numeric(as.POSIXct(as.Date(datesportfolio[d + 1]),
format = "%Y-%m-%d"
)), "&interval=1d&events=history&includeAdjustedClose=true"
)
# paste0('https://finance.yahoo.com/quote/',df_tranch_portfolio[[d]][[s]][k],'/history?period1=',as.numeric(as.POSIXct(as.Date(format(as.Date(datesportfolio[d])-30, '%Y-%m-01')), format="%Y-%m-%d")),'&period2=',as.numeric(as.POSIXct(as.Date(datesportfolio[d+1]), format="%Y-%m-%d")),'&interval=1d&events=history&includeAdjustedClose=true')
options(HTTPUserAgent = temp_uagent)
Sys.sleep(sample(30, 1) * 0.1)
flat_html <- tryCatch(read.csv(file = url(txt_address), sep = ","), error = function(e) TRUE)
if (is.logical(flat_html) != TRUE) {
cc <- cc + 1
# temp_q<-data.frame(as.Date(flat_html$Date),as.numeric(flat_html$Adj.Close))
# usar Adj.Close en lugar de Close puede dar lugar a extranhos valores, como por ejemplo: https://finance.yahoo.com/quote/KPO.F/history?period1=1410566400&period2=1414454400&interval=1d&filter=history&frequency=1d&includeAdjustedClose=true
# https://finance.yahoo.com/quote/SZD.F/history?period1=1410566400&period2=1413158400&interval=1d&filter=history&frequency=1d&includeAdjustedClose=true
temp_q <- data.frame(as.Date(flat_html$Date), as.numeric(flat_html$Close))
colnames(temp_q) <- c("Dates", df_tranch_portfolio[[d]][[s]][k])
if (cc == 1) {
temp_portfolio <- temp_q
} else {
temp_portfolio <- merge(x = temp_portfolio, y = temp_q, by = "Dates", all = TRUE)
}
}
print(paste0("Building ", namesSubportfolios[s], " in ", month(as.Date(datesportfolio[d]), label = TRUE, abbr = FALSE), ", year: ", year(as.Date(datesportfolio[d])), " - Completed ", sprintf("%0.2f%%", k / length(df_tranch_portfolio[[d]][[s]]) * 100)))
}
temp_path <- apply(temp_portfolio[, -1], 1, mean, na.rm = TRUE)
if (d == 1) {
id_min <- min(which(((temp_portfolio$Dates >= as.Date(datesportfolio[d])) & (temp_portfolio$Dates <= as.Date(datesportfolio[d + 1]))))) - 1
id_max <- max(which(((temp_portfolio$Dates >= as.Date(datesportfolio[d])) & (temp_portfolio$Dates <= as.Date(datesportfolio[d + 1])))))
portfolio_series[[s]] <- list(Dates = temp_portfolio$Dates[c(id_min:id_max)], Price = c(100, temp_path[c((id_min + 1):id_max)] / temp_path[id_min] * 100))
} else {
id_min <- min(which(((temp_portfolio$Dates >= as.Date(datesportfolio[d])) & (temp_portfolio$Dates <= as.Date(datesportfolio[d + 1]))))) - 1
id_max <- max(which(((temp_portfolio$Dates >= as.Date(datesportfolio[d])) & (temp_portfolio$Dates <= as.Date(datesportfolio[d + 1])))))
Stockportfolio <- data.frame(temp_portfolio$Dates[c((id_min + 1):id_max)], temp_path[c((id_min + 1):id_max)] * portfolio_series[[s]][[2]][length(portfolio_series[[s]][[2]])] / temp_path[id_min])
colnames(Stockportfolio) <- c("Dates", "Price")
portfolio_series[[s]] <- rbind(portfolio_series[[s]], Stockportfolio)
rm(Stockportfolio)
}
# rm(temp_portfolio,trym,temp_q,temp_path,id_min,id_max)
} else {
cc <- 0
for (k in c(1:length(df_tranch_portfolio[[d]][[s]]))) {
temp_uagent <- uagent[sample(5, 1)]
txt_address <- paste0(
"https://query1.finance.yahoo.com/v7/finance/download/",
df_tranch_portfolio[[d]][[s]][k], "?period1=",
as.numeric(as.POSIXct(as.Date(format(as.Date(datesportfolio[d]) - 30, "%Y-%m-01")), format = "%Y-%m-%d")), "&period2=",
as.numeric(as.POSIXct(as.Date(Sys.Date()), format = "%Y-%m-%d")), "&interval=1d&events=history&includeAdjustedClose=true"
)
# paste0('https://finance.yahoo.com/quote/',df_tranch_portfolio[[d]][[s]][k],'/history?period1=',as.numeric(as.POSIXct(as.Date(format(as.Date(datesportfolio[d])-30, '%Y-%m-01')), format="%Y-%m-%d")),'&period2=',as.numeric(as.POSIXct(as.Date(datesportfolio[d+1]), format="%Y-%m-%d")),'&interval=1d&events=history&includeAdjustedClose=true')
options(HTTPUserAgent = temp_uagent)
Sys.sleep(sample(10, 1) * 0.1)
flat_html <- tryCatch(read.csv(file = url(txt_address), sep = ","), error = function(e) TRUE)
if (is.logical(flat_html) != TRUE) {
cc <- cc + 1
# temp_q<-data.frame(as.Date(flat_html$Date),as.numeric(flat_html$Adj.Close))
# usar Adj.Close en lugar de Close puede dar lugar a extranhos valores, como por ejemplo: https://finance.yahoo.com/quote/KPO.F/history?period1=1410566400&period2=1414454400&interval=1d&filter=history&frequency=1d&includeAdjustedClose=true
# https://finance.yahoo.com/quote/SZD.F/history?period1=1410566400&period2=1413158400&interval=1d&filter=history&frequency=1d&includeAdjustedClose=true
temp_q <- data.frame(as.Date(flat_html$Date), as.numeric(flat_html$Close))
colnames(temp_q) <- c("Dates", df_tranch_portfolio[[d]][[s]][k])
if (cc == 1) {
temp_portfolio <- temp_q
} else {
temp_portfolio <- merge(x = temp_portfolio, y = temp_q, by = "Dates", all = TRUE)
}
}
print(paste0(
"Building ", namesSubportfolios[s], " in ",
month(as.Date(datesportfolio[d]), label = TRUE, abbr = FALSE), ", year: ",
year(as.Date(datesportfolio[d])), " - Completed ", sprintf(
"%0.2f%%",
k / length(df_tranch_portfolio[[d]][[s]]) * 100
)
))
}
temp_path <- apply(temp_portfolio[, -1], 1, mean, na.rm = TRUE)
id_min <- min(which(temp_portfolio$Dates >= as.Date(datesportfolio[d]))) - 1
id_max <- max(which(temp_portfolio$Dates >= as.Date(datesportfolio[d])))
Stockportfolio <- data.frame(temp_portfolio$Dates[c((id_min + 1):id_max)], temp_path[c((id_min + 1):id_max)] * portfolio_series[[s]][[2]][length(portfolio_series[[s]][[2]])] / temp_path[id_min])
colnames(Stockportfolio) <- c("Dates", "Price")
portfolio_series[[s]] <- rbind(portfolio_series[[s]], Stockportfolio)
rm(Stockportfolio)
}
}
}
# Guardamos los datos finales
save(financial_quotes, portfolio_series, file = "Quotes.RData")