#Cargar librerias
library(lubridate)
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
library(tseries)
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(lubridate)
library(tidyverse)
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v ggplot2 3.3.5     v purrr   0.3.4
## v tibble  3.1.2     v dplyr   1.0.7
## v tidyr   1.1.3     v stringr 1.4.0
## v readr   1.4.0     v forcats 0.5.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x lubridate::as.difftime() masks base::as.difftime()
## x lubridate::date()        masks base::date()
## x dplyr::filter()          masks stats::filter()
## x lubridate::intersect()   masks base::intersect()
## x dplyr::lag()             masks stats::lag()
## x lubridate::setdiff()     masks base::setdiff()
## x lubridate::union()       masks base::union()
library(car)
## Loading required package: carData
## 
## Attaching package: 'car'
## The following object is masked from 'package:dplyr':
## 
##     recode
## The following object is masked from 'package:purrr':
## 
##     some
library(astsa)
library(foreign)
library(timsac)
library(vars)
## Loading required package: MASS
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
## 
##     select
## Loading required package: strucchange
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## Loading required package: sandwich
## 
## Attaching package: 'strucchange'
## The following object is masked from 'package:stringr':
## 
##     boundary
## Loading required package: urca
## Loading required package: lmtest
library(lmtest)
library(mFilter)
library(dynlm)
library(nlme)
## 
## Attaching package: 'nlme'
## The following object is masked from 'package:dplyr':
## 
##     collapse
library(lmtest)
library(broom)
library(kableExtra)
## 
## Attaching package: 'kableExtra'
## The following object is masked from 'package:dplyr':
## 
##     group_rows
library(knitr)
library(MASS)
library(parallel)
library(car)
library(mlogit)
## Loading required package: dfidx
## 
## Attaching package: 'dfidx'
## The following object is masked from 'package:MASS':
## 
##     select
## The following object is masked from 'package:stats':
## 
##     filter
library(dplyr)
library(tidyr)
library(forecast)
## 
## Attaching package: 'forecast'
## The following object is masked from 'package:nlme':
## 
##     getResponse
## The following object is masked from 'package:astsa':
## 
##     gas
library(fpp2)
## -- Attaching packages ---------------------------------------------- fpp2 2.4 --
## v fma       2.4     v expsmooth 2.3
## -- Conflicts ------------------------------------------------- fpp2_conflicts --
## x forecast::getResponse() masks nlme::getResponse()
## x car::some()             masks purrr::some()
## 
## Attaching package: 'fpp2'
## The following object is masked from 'package:astsa':
## 
##     oil
library(stats)
library(quantmod)
## Loading required package: xts
## 
## Attaching package: 'xts'
## The following objects are masked from 'package:dplyr':
## 
##     first, last
## Loading required package: TTR
library(readxl)
Arimar <- read_excel("D:/Arimar.xlsx")
View(Arimar)
attach(Arimar)
names(Arimar)
## [1] "Precio"
#Series de Tiempo Univariadas 

#Paso 1. Convertir a objeto de Serie de Tiempo en R

Arimar.ts=ts(Arimar, start=c(2013,1), frequency = 12)

print(Arimar.ts)
##            Jan       Feb       Mar       Apr       May       Jun       Jul
## 2013  97.98278 103.35294 100.77090  97.75538  97.90686  96.99315  99.67255
## 2014  88.31081  90.82224  91.39522  93.88863  95.08631  97.01105  93.32017
## 2015  40.45127  45.98606  46.01733  49.32555  52.03910  52.82573  45.16595
## 2016  23.10238  23.72933  28.32656  31.33582  36.72636  39.80715  37.97153
## 2017  44.50008  44.17497  41.93243  43.22118  43.85074  41.15105  43.87771
## 2018  57.45399  56.15676  57.22458  58.15973  62.89929  64.63686  66.42162
## 2019  54.05666  57.37981  59.46449  62.07703  60.33674  56.90537  57.87580
## 2020  49.79299  44.63505  28.92302                                        
##            Aug       Sep       Oct       Nov       Dec
## 2013  99.24414  98.14572  93.87329  88.48590  89.40966
## 2014  89.50745  84.12824  72.50936  63.47980  50.18138
## 2015  38.41927  36.29036  34.86077  32.50883  26.19610
## 2016  37.74090  36.82666  40.66836  38.36162  42.32596
## 2017  45.55484  48.16237  48.89114  53.34505  54.05576
## 2018  64.26567  68.36348  71.15330  59.82583  51.86867
## 2019  49.58496  55.05522  51.00463  50.68969  54.54901
## 2020
#library(rio)
#export(Arimar.ts,"Arimar.ts.xlsx")
library(readxl)
df <- read_excel("Arimarlevene.xlsx")
df$mes=as.factor(df$mes)
#shapiro.test(df$Precio)
leveneTest(df$Precio~df$mes,data = df)
getwd()
## [1] "C:/Users/DELL/Desktop/para series de tiempo 2021"
library(readxl)
k <- read_excel("kruskall.xlsx")
head(k)
#View(k)
k$mes=as.factor(k$mes)
#Ho:La serie no posee componente estacional. 
#H1:La series  posee componente estacional.
kruskal.test(k$Precio~k$mes)
## 
##  Kruskal-Wallis rank sum test
## 
## data:  k$Precio by k$mes
## Kruskal-Wallis chi-squared = 3.0289, df = 1, p-value = 0.08179
tapply(k$Precio, k$mes, median)
##        1        2 
## 72.50936 52.60686
BoxCox.lambda(Arimar.ts)
## [1] 0.05546431
class(Arimar.ts)
## [1] "ts"
start(Arimar.ts)
## [1] 2013    1
end(Arimar.ts)
## [1] 2020    3
plot(Arimar.ts,  main="Serie de tiempo", ylab="Precio", col="red")

library(TSstudio)
ts_plot(Arimar.ts)
tsdisplay(Arimar.ts)

ts_seasonal(Arimar.ts)
ggseasonplot(Arimar.ts, year.labels=TRUE, year.labels.left=TRUE) +
ylab("$ Precios") +
ggtitle("Seasonal plot")

ggsubseriesplot(Arimar.ts) +
ylab("$ Precios") +
ggtitle("Seasonal subseries plot")

serielog=log(Arimar.ts)
serielog
##           Jan      Feb      Mar      Apr      May      Jun      Jul      Aug
## 2013 4.584792 4.638150 4.612850 4.582468 4.584017 4.574640 4.601890 4.597583
## 2014 4.480862 4.508904 4.515193 4.542109 4.554785 4.574825 4.536036 4.494322
## 2015 3.700098 3.828338 3.829018 3.898442 3.951995 3.966998 3.810343 3.648559
## 2016 3.139936 3.166712 3.343800 3.444762 3.603495 3.684046 3.636837 3.630744
## 2017 3.795491 3.788158 3.736059 3.766331 3.780792 3.717249 3.781407 3.818917
## 2018 4.050985 4.028147 4.046984 4.063193 4.141535 4.168785 4.196023 4.163026
## 2019 3.990033 4.049692 4.085379 4.128376 4.099941 4.041390 4.058299 3.903688
## 2020 3.907874 3.798519 3.364638                                             
##           Sep      Oct      Nov      Dec
## 2013 4.586453 4.541946 4.482843 4.493229
## 2014 4.432342 4.283716 4.150722 3.915644
## 2015 3.591552 3.551362 3.481512 3.265610
## 2016 3.606222 3.705450 3.647058 3.745401
## 2017 3.874578 3.889596 3.976781 3.990016
## 2018 4.224839 4.264837 4.091438 3.948715
## 2019 4.008337 3.931916 3.925723 3.999100
## 2020
plot(serielog)

#Estacionariedad: Para conocer el número de diferencias que se requieren para lograr que la serie 
#sea estacionaria
library(forecast)
ndiffs(Arimar.ts)
## [1] 1
#Estacionariedad: Para conocer el número de diferencias que se requieren para lograr que la serie 
#sea estacionaria

nsdiffs(Arimar.ts)
## [1] 0
#Paso 2.Prueba de DickeyFuller

adf.test(Arimar.ts)
## 
##  Augmented Dickey-Fuller Test
## 
## data:  Arimar.ts
## Dickey-Fuller = -1.6185, Lag order = 4, p-value = 0.7328
## alternative hypothesis: stationary
seriedif=diff(Arimar.ts)
plot(seriedif)

acf(seriedif)

library(fpp2)
ggAcf(Arimar.ts,lag=48)

library(TSstudio)
ndiffs(seriedif)
## [1] 0
adf.test(seriedif)
## 
##  Augmented Dickey-Fuller Test
## 
## data:  seriedif
## Dickey-Fuller = -3.3327, Lag order = 4, p-value = 0.07162
## alternative hypothesis: stationary
#Prueba de Dickey Fuller con dos diferencias


seriedif2=diff(Arimar.ts, differences =2)
plot(seriedif2)

adf.test(seriedif2)
## Warning in adf.test(seriedif2): p-value smaller than printed p-value
## 
##  Augmented Dickey-Fuller Test
## 
## data:  seriedif2
## Dickey-Fuller = -5.1673, Lag order = 4, p-value = 0.01
## alternative hypothesis: stationary
plot(seriedif2, type="o", lty="dashed",main="Serie de Tiempo",col="red")

par(mfrow=c(2,1), mar=c(4,4,4,1)+.1)
acf(seriedif2)
pacf(seriedif2)

acf(ts(seriedif2, frequency=1))
pacf(ts(seriedif2, frequency=1))

#Modelo Arima

modelo1=arima(Arimar.ts,order=c(1,2,1))
summary(modelo1)
## 
## Call:
## arima(x = Arimar.ts, order = c(1, 2, 1))
## 
## Coefficients:
##          ar1     ma1
##       0.4173  -1.000
## s.e.  0.1100   0.047
## 
## sigma^2 estimated as 17.51:  log likelihood = -244.07,  aic = 494.14
## 
## Training set error measures:
##                      ME     RMSE      MAE        MPE     MAPE      MASE
## Training set -0.1842755 4.136183 3.135096 -0.2061955 6.279221 0.9152235
##                     ACF1
## Training set -0.02472726
modelo1
## 
## Call:
## arima(x = Arimar.ts, order = c(1, 2, 1))
## 
## Coefficients:
##          ar1     ma1
##       0.4173  -1.000
## s.e.  0.1100   0.047
## 
## sigma^2 estimated as 17.51:  log likelihood = -244.07,  aic = 494.14
tsdiag(modelo1)

Box.test(residuals(modelo1),type="Ljung-Box")
## 
##  Box-Ljung test
## 
## data:  residuals(modelo1)
## X-squared = 0.055051, df = 1, p-value = 0.8145
error=residuals(modelo1)
plot(error)

#Pronosticos Arima
pronostico=forecast::forecast(modelo1,h=16)
pronostico
##          Point Forecast       Lo 80    Hi 80      Lo 95    Hi 95
## Apr 2020      21.856654  16.4633719 27.24994  13.608341 30.10497
## May 2020      18.398192   8.9934192 27.80296   4.014833 32.78155
## Jun 2020      16.445341   3.6136910 29.27699  -3.178974 36.06966
## Jul 2020      15.120795  -0.6776994 30.91929  -9.040917 39.28251
## Aug 2020      14.058445  -4.3652157 32.48211 -14.118113 42.23500
## Sep 2020      13.105513  -7.6904599 33.90149 -18.699183 44.91021
## Oct 2020      12.198241 -10.7797404 35.17622 -22.943549 47.34003
## Nov 2020      11.310024 -13.7033148 36.32336 -26.944576 49.56462
## Dec 2020      10.429758 -16.5031190 37.36264 -30.760523 51.62004
## Jan 2021       9.552811 -19.2060240 38.31165 -34.430032 53.53565
## Feb 2021       8.677249 -21.8303878 39.18488 -37.980155 55.33465
## Mar 2021       7.802264 -24.3894412 39.99397 -41.430701 57.03523
## Apr 2021       6.927520 -26.8931307 40.74817 -44.796702 58.65174
## May 2021       6.052878 -29.3491818 41.45494 -48.089900 60.19566
## Jun 2021       5.178277 -31.7637487 42.12030 -51.319676 61.67623
## Jul 2021       4.303693 -34.1418321 42.74922 -54.493664 63.10105
plot(pronostico)