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-01-01"),to=as.Date("2022-01-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-01-02   198.00   200.80  197.81    200.79    3554200     185.2633
## 2020-01-03   199.39   200.55  198.85    200.08    2767600     184.6082
## 2020-01-06   199.60   202.77  199.35    202.33    4660400     186.6842
## 2020-01-07   201.87   202.68  200.51    202.63    4047400     186.9610
## 2020-01-08   202.62   206.69  202.20    205.91    5284200     189.9874
## 2020-01-09   206.86   209.37  206.10    208.35    5971600     192.2387
##                tiempo
## 2020-01-02 2020-01-02
## 2020-01-03 2020-01-03
## 2020-01-06 2020-01-06
## 2020-01-07 2020-01-07
## 2020-01-08 2020-01-08
## 2020-01-09 2020-01-09
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-01-02 200.79
## 2  2020-01-03 200.08
## 3  2020-01-06 202.33
## 4  2020-01-07 202.63
## 5  2020-01-08 205.91
## 6  2020-01-09 208.35
## 7  2020-01-10 207.27
## 8  2020-01-13 206.51
## 9  2020-01-14 207.32
## 10 2020-01-15 209.77

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.1901, Lag order = 7, p-value = 0.08964
## 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) = -19.381, Truncation lag parameter = 5, p-value
## = 0.08117
## 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.4103, Lag order = 7, 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(2,1,3) with drift 
## 
## Coefficients:
##           ar1      ar2     ma1     ma2     ma3   drift
##       -1.7013  -0.8612  1.6012  0.7286  0.0178  0.1339
## s.e.   0.0553   0.0477  0.0720  0.0842  0.0483  0.1366
## 
## sigma^2 = 10.78:  log likelihood = -1311.7
## AIC=2637.41   AICc=2637.63   BIC=2666.96
tsdisplay(residuals(modeloarima), lag.max=10, main='(2,1,3) Model Residuals')

CUARTA ETAPA: Predicción

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

tail(prediccion$mean,30)
## Time Series:
## Start = c(17, 26) 
## End = c(18, 25) 
## Frequency = 30 
##  [1] 268.2279 268.1453 268.6385 268.3476 268.8947 268.6914 269.0431 269.0968
##  [9] 269.1796 269.4696 269.3820 269.7583 269.6705 269.9727 270.0111 270.1625
## [17] 270.3489 270.3785 270.6446 270.6433 270.8934 270.9461 271.1180 271.2571
## [25] 271.3494 271.5496 271.6066 271.8143 271.8888 272.0601