La presente públicación tiene como objetivo orientar a quienes tengan inconvenientes para poder pasar de datos en formato xts a un data.frame. Como ejemplo principal, se utilizará la libreria quantmod, ggplot2, xts, zoo, tidyverse y una función elaborada para poder pasar de xts a data.frame.
library(quantmod)
## Loading required package: xts
## Loading required package: zoo
##
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
## Version 0.4-0 included new data defaults. See ?getSymbols.
library(xts)
library(ggplot2)
library(tidyverse)
## -- Attaching packages --------------------------------------------------------------------------------------------------------------- tidyverse 1.3.0 --
## v tibble 3.0.3 v dplyr 1.0.2
## v tidyr 1.1.2 v stringr 1.4.0
## v readr 1.4.0 v forcats 0.5.0
## v purrr 0.3.4
## -- Conflicts ------------------------------------------------------------------------------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::first() masks xts::first()
## x dplyr::lag() masks stats::lag()
## x dplyr::last() masks xts::last()
library(zoo)
library(lubridate)
##
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
getSymbols("^MXX", src = "yahoo",
from= "2006-01-01",
to="2020-10-27",
periodicity="daily",
format="xts")
## 'getSymbols' currently uses auto.assign=TRUE by default, but will
## use auto.assign=FALSE in 0.5-0. You will still be able to use
## 'loadSymbols' to automatically load data. getOption("getSymbols.env")
## and getOption("getSymbols.auto.assign") will still be checked for
## alternate defaults.
##
## This message is shown once per session and may be disabled by setting
## options("getSymbols.warning4.0"=FALSE). See ?getSymbols for details.
## Warning: ^MXX contains missing values. Some functions will not work if objects
## contain missing values in the middle of the series. Consider using na.omit(),
## na.approx(), na.fill(), etc to remove or replace them.
## [1] "^MXX"
# Comprobamos que la serie este en formato XTS
class(MXX)
## [1] "xts" "zoo"
Una vez que ya comprobamos que la serie esta correctamente al formato xts, procederemos al punto 2.
Hacemos uso de la programación para elaborar una función que nos devuelva un dataframe de una serie xts:
xts_to_datframe<-function(data_xts){
df_t<-data.frame(fecha=(index(data_xts)),
value=coredata(data_xts))
colnames(df_t)<-c("fecha", "value")
df_t
}
# index(data_xts): es una declaración que toma el tiempo de una serie xts diaria.
#coredata(data_xts): es una declaración que toma los valores de la serie xts diaria.
#colnames (df_t): para renombrar las columnas que se crearan en el dataframe
Una vez que se crea la función, la utilizaremos para trasformar la serie:
IPC<-xts_to_datframe(MXX$MXX.Adjusted)
#MXX$MXX.Adjusted es la variable xts que utilizaremos
head(IPC)
Gráficaremos el dataframe para corroborar que la transformación fue efectiva:
ggplot(IPC, aes(x=fecha, y=value))+
geom_line()+
theme_minimal()+
labs(title="IPC BMV S&P 500",
subtitle = "De 2006 a 2020",
caption = "Elaboración propia con datos de Yahoo Finanzas")
La pregunta es ¿De qué sirve trabajar con dataframe si ya están los datos en formato de series temporales? La respuesta se remite a que las aplicaciones de tydiverse y ggplot, nos puede ayudar para un análisis exploratorio de la serie temporal, tal como rendimientos anuales, varianzas anualizadas, etc. A continuación dejaré unos ejemplos.
ts_IPC<-ts(IPC$value, star=c(2006,1,1),frequency = 256)
fechas<-as.Date(IPC$fecha)
xts_IPC<-xts(x=IPC$value, order.by = fechas)
head(xts_IPC)
## [,1]
## 2006-01-02 17925.70
## 2006-01-03 18500.69
## 2006-01-04 18669.23
## 2006-01-05 18608.34
## 2006-01-06 18736.78
## 2006-01-09 18998.83
IPC_retardos<- IPC %>%
mutate(fecha=ymd(fecha),
retardo1=lag(value, k=1),
adelanto1=lag(value,k=1),
d1=diff(xts_IPC, differences = 1),
d2=diff(xts_IPC, differences = 2),
d1log=log(value)-lag(log(value)),
tc_relativa=((value/lag(value,1))-1)*100)
head(IPC_retardos)
diff(xts_IPC, differences = 1) %>%
autoplot()+
theme_minimal()+
labs(title="Retornos del IPC S&P500",
subtitle = "Del 2006 al 2020",
caption = "Elaboración propia con tados de yahoo finanzas")
## Warning: Removed 1 row(s) containing missing values (geom_path).
IPC_d<-IPC %>%
mutate(anio=format(fecha, "%Y"),
dia_semana=format(fecha, "%A"),
dia_semana_num=wday(fecha),
dia_mes=format(fecha, "%d"),
semana=format(fecha,"%W"),
mes_tex=format(fecha, "%b"),
mes_num=format(fecha, "%m"),
trimestre=as.yearqtr(fecha,"%Q"),
tc_IPC=(value/lag(value,1)-1)*100)
IPC_d %>% head(n=2)
IPC_d %>%
group_by(anio) %>%
summarise(promedio_posi=mean(tc_IPC[tc_IPC>0], na.rm=TRUE),
promedio_nega=mean(tc_IPC[tc_IPC<=0],na.rm = TRUE),
promedio_total=mean(tc_IPC, na.rm = TRUE)) %>%
tail()
## `summarise()` ungrouping output (override with `.groups` argument)
Seleccionamos año 2019
IPC_d %>%
mutate(nombre_mes=month(fecha, label = TRUE)) %>%
filter(anio==2019) %>%
group_by(nombre_mes) %>%
summarise(prom_mes=mean(value, na.rm = TRUE)) %>%
ggplot(aes(x=nombre_mes, y=prom_mes))+
geom_bar(stat = "identity", fill="steelblue")+
geom_text(aes(label=round(prom_mes,2)), vjust=1.6, colour="white")+
theme_minimal()
## `summarise()` ungrouping output (override with `.groups` argument)
IPC_d %>%
mutate(nombre_mes=month(fecha, label=TRUE)) %>%
filter(anio==2019) %>%
ggplot(aes(x=nombre_mes, y=tc_IPC))+
geom_boxplot(fill="blue")+
theme_minimal()
IPC_d %>%
group_by(anio) %>%
ggplot(aes(x=anio, y=tc_IPC))+
geom_boxplot(fill="white", colour="#3366FF", outlier.color = "red")+
theme_minimal()+
labs(title="Distribución histórica de los rendimientos del IPC S&P 500",
subtitle = "Gráfico de caja del 2006 al 2019",
caption = "Elaboración propia con datos de Yahoo Finanzas")
## Warning: Removed 38 rows containing non-finite values (stat_boxplot).
Por ultimo, podemos hacer gráficas de la serie convertida de dataframe a xts con la libreria quantmod, esto con la finalidad de quienes opten por gráficar la serie con esta libreria. Como recordatorio solo podemos gráficar la serie histórica diaria y los retornos.
# Serie historica
chartSeries(xts_IPC, type = "line",
theme = "white")
library(PerformanceAnalytics)
##
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
##
## legend
# Retornos
r_IPC<-Return.calculate(xts_IPC, method = "log") %>% na.omit
chartSeries(r_IPC,
type = "line",
theme = "white")