Introducción

La base de datos para el siguiente análsisi es extraído de Yahoo Finance (a través de la técnica scraping) y trata sobre el precio de las acciones de McDonalds.

Instalación de librerias

#install.packages('quantmod') # librería para hacer scraping
#install.packages('tseries')
#install.packages('timeSeries')
#install.packages('forecast')
#install.packages('xts')
#install.packages('ggplot2')

Ejecutando las librerías

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
library(tseries)
library(timeSeries)
## Loading required package: timeDate
## 
## Attaching package: 'timeSeries'
## The following object is masked from 'package:zoo':
## 
##     time<-
library(forecast)
library(xts)
library(ggplot2)

PRIMERA ETAPA: Identificación

MCD <- getSymbols('MCD', src='yahoo', from = as.Date("2020-12-01"),to=as.Date("2023-07-01"), auto.assign = FALSE)

Graficando la serie

chartSeries(MCD, name="MCD", subset="last 6 months", theme=chartTheme("white"))

Datos de yahoo finance:

data_MCD <- data.frame(MCD, tiempo = as.Date(rownames(data.frame(MCD))))
head(data_MCD)
##            MCD.Open MCD.High MCD.Low MCD.Close MCD.Volume MCD.Adjusted
## 2020-12-01   218.88   218.93  215.53    216.14    4224800     204.4019
## 2020-12-02   214.00   214.40  209.13    210.86    6223700     199.4086
## 2020-12-03   210.94   213.23  210.56    211.51    3732500     200.0233
## 2020-12-04   211.60   213.38  210.10    210.74    3151100     199.2951
## 2020-12-07   208.53   209.11  206.19    208.89    3826000     197.5456
## 2020-12-08   206.55   209.10  206.41    208.39    2709400     197.0727
##                tiempo
## 2020-12-01 2020-12-01
## 2020-12-02 2020-12-02
## 2020-12-03 2020-12-03
## 2020-12-04 2020-12-04
## 2020-12-07 2020-12-07
## 2020-12-08 2020-12-08
attach(data_MCD)

Separando la serie close:

base1 = data.frame(tiempo, MCD.Close)
names (base1) = c("tiempo","MCD")
base1 <- na.omit(base1) #eliminando datos ominitidos "NA"
#base1
head(base1, n = 10)
##        tiempo    MCD
## 1  2020-12-01 216.14
## 2  2020-12-02 210.86
## 3  2020-12-03 211.51
## 4  2020-12-04 210.74
## 5  2020-12-07 208.89
## 6  2020-12-08 208.39
## 7  2020-12-09 208.69
## 8  2020-12-10 208.04
## 9  2020-12-11 207.76
## 10 2020-12-14 211.92

Graficando la serie

ggplot(base1, aes(x = tiempo, y =  MCD)) + geom_line() + geom_smooth(se = FALSE)+ labs(title = "Precio de las acciones de McDonalds", x = "Fecha", y = "Precio / Acción")
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

MCD_ma = ts(na.omit(base1$MCD), frequency=30)
decomp = stl(MCD_ma, s.window="periodic")
deseasonal_base1 <- seasadj(decomp)
plot(decomp)

SEGUNDA ETAPA: Análisis y diferenciación de la serie temporal

adf.test(MCD_ma, alternative = "stationary")
## 
##  Augmented Dickey-Fuller Test
## 
## data:  MCD_ma
## Dickey-Fuller = -3.3386, Lag order = 8, p-value = 0.06403
## alternative hypothesis: stationary

Contraste de hipótesis:

pp.test(MCD_ma, alternative = "stationary")
## 
##  Phillips-Perron Unit Root Test
## 
## data:  MCD_ma
## Dickey-Fuller Z(alpha) = -22.498, Truncation lag parameter = 6, p-value
## = 0.04244
## alternative hypothesis: stationary

Contraste de hipótesis:

Continuamos con las autocorrelaciones.

Las ACF proporcionan información sobre cómo una observación influye en las siguientes.

Acf(MCD_ma, main='')

Pacf(MCD_ma, main='')

Diferenciación de la serie

Para realizar un modelo ARIMA, la serie temporal debe ser estacionaria. Para conseguir esta estacionariedad, la diferenciaremos.

MCD_d1 = diff(deseasonal_base1, differences = 1)
plot(MCD_d1)

Para comprobar que la serie es, efectivamente, estacionaria, hacemos de nuevo el test aumentado de Dickey-Fuller.

adf.test(MCD_d1, alternative = "stationary")
## Warning in adf.test(MCD_d1, alternative = "stationary"): p-value smaller than
## printed p-value
## 
##  Augmented Dickey-Fuller Test
## 
## data:  MCD_d1
## Dickey-Fuller = -8.4168, Lag order = 8, p-value = 0.01
## alternative hypothesis: stationary

TERCERA ETAPA: Ajuste de un modelo ARIMA.

modeloarima<-auto.arima(MCD_ma, seasonal=FALSE)
modeloarima
## Series: MCD_ma 
## ARIMA(1,1,0) 
## 
## Coefficients:
##           ar1
##       -0.0077
## s.e.   0.0394
## 
## sigma^2 = 6.976:  log likelihood = -1548.33
## AIC=3100.65   AICc=3100.67   BIC=3109.6
tsdisplay(residuals(modeloarima), lag.max=10, main='(0,1,0) Model Residuals')

CUARTA ETAPA: Predicción

prediccion <- forecast(modeloarima, h=30)
plot(prediccion)

tail(prediccion$mean,30)
## Time Series:
## Start = c(22, 20) 
## End = c(23, 19) 
## Frequency = 30 
##  [1] 298.3798 298.3800 298.3800 298.3800 298.3800 298.3800 298.3800 298.3800
##  [9] 298.3800 298.3800 298.3800 298.3800 298.3800 298.3800 298.3800 298.3800
## [17] 298.3800 298.3800 298.3800 298.3800 298.3800 298.3800 298.3800 298.3800
## [25] 298.3800 298.3800 298.3800 298.3800 298.3800 298.3800