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("2021-01-01"),to=as.Date("2023-07-27"), 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
## 2021-01-04   214.49   214.72  208.22    210.22    4055400     198.8033
## 2021-01-05   210.18   211.95  209.62    211.48    2576100     199.9949
## 2021-01-06   211.30   211.71  209.03    211.00    3083400     199.5410
## 2021-01-07   213.22   213.22  210.56    211.98    3142000     200.4678
## 2021-01-08   212.90   216.12  212.23    215.87    2639100     204.1465
## 2021-01-11   215.09   216.12  213.12    214.23    2545400     202.5956
##                tiempo
## 2021-01-04 2021-01-04
## 2021-01-05 2021-01-05
## 2021-01-06 2021-01-06
## 2021-01-07 2021-01-07
## 2021-01-08 2021-01-08
## 2021-01-11 2021-01-11
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  2021-01-04 210.22
## 2  2021-01-05 211.48
## 3  2021-01-06 211.00
## 4  2021-01-07 211.98
## 5  2021-01-08 215.87
## 6  2021-01-11 214.23
## 7  2021-01-12 211.60
## 8  2021-01-13 212.09
## 9  2021-01-14 208.50
## 10 2021-01-15 209.91

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.4784, Lag order = 8, p-value = 0.04438
## 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.836, Truncation lag parameter = 6, p-value
## = 0.03988
## 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.3573, 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(0,1,0) 
## 
## sigma^2 = 6.935:  log likelihood = -1535
## AIC=3071.99   AICc=3072   BIC=3076.46
tsdisplay(residuals(modeloarima), lag.max=10, main='(0,1,0) Model Residuals')

El modelo ARIMA es correcto, pues tiene una tendencia creciente y su modelo es 0,1,0. Donde en parte nos indica que no hay errores o innovaciones (0)

CUARTA ETAPA: Predicción

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

tail(prediccion$mean,30)
## Time Series:
## Start = c(22, 15) 
## End = c(23, 14) 
## Frequency = 30 
##  [1] 291.75 291.75 291.75 291.75 291.75 291.75 291.75 291.75 291.75 291.75
## [11] 291.75 291.75 291.75 291.75 291.75 291.75 291.75 291.75 291.75 291.75
## [21] 291.75 291.75 291.75 291.75 291.75 291.75 291.75 291.75 291.75 291.75