##Carga de Datos

BTCSP <- read.csv("C:/Users/Personal/Desktop/BTCSP.csv", sep=";")
apple<-BTCSP
head(apple)
##         Date BTC.Close SP.Close
## 1 01.01.2014     740.3  1842.95
## 2 02.01.2014     775.0  1826.50
## 3 03.01.2014     812.1  1825.50
## 4 06.01.2014     934.5  1820.75
## 5 07.01.2014     791.0  1830.75
## 6 08.01.2014     828.5  1832.50
tail(apple)
##            Date BTC.Close SP.Close
## 1599 24.01.2020    8447.1  3293.50
## 1600 26.01.2020    8621.6  3259.12
## 1601 27.01.2020    8912.0  3239.50
## 1602 28.01.2020    9393.7  3278.25
## 1603 29.01.2020    9304.2  3272.50
## 1604 30.01.2020    9512.7  3289.38

##Activación Paquete Zoo

library(zoo)
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
apple.zoo=zoo(apple[,-1], order.by=as.Date(strptime(as.character(apple[,1]), "%d.%m.%Y")))
plot(apple.zoo, main="Precios de Cierre BTC y S&P 500 (2014-2020)")

##Función Rollapply ##Gráfica para visualizar Tendencias

library(chron)
plot(rollapply(apple.zoo, width=120, mean, na.rm=T), main="Mean of Rolling  120 Obs.")

plot(rollapply(apple.zoo, width=120, mean, by=120, na.rm=T),main="Mean of Each 120 Obs.")

##Análisis de Retornos

library(PerformanceAnalytics)
## Loading required package: xts
## 
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
## 
##     legend
tmp <- merge(apple.zoo[,"BTC.Close"], apple.zoo[,"SP.Close"])
tmp.ret <- CalculateReturns(tmp)
colnames(tmp) <- colnames(tmp.ret) <- c("BTC.Close","SP.Close")
plot(tmp.ret, main="Retornos Precios Cierre BTC y S&P 500 (2014-2020)", xlab="Date")

##Función coredata

plot(coredata(na.omit(tmp.ret)), pch=".", main="Retornos Precios Cierre BTC y S&P 500 (2014-2020)")

##Coeficientes de regresión

rr <- rollapply(na.approx(na.trim(tmp, side="both")), width = 120,
                FUN = function(z) coef(lm(BTC.Close ~ SP.Close, data = as.data.frame(z))),
                by.column = FALSE, align = "right")

rr.var <- rollapply(na.approx(na.trim(tmp, side="both")), width = 120,
                    FUN = function(z) sd(residuals(lm(BTC.Close ~ SP.Close, data = as.data.frame(z)))),
                    by.column = FALSE, align = "right")

res <- merge(rr,rr.var)
colnames(res)[3] <- "Desv  Estandar Res." 
plot(res, main="Coeficiente de Regresion.", xlab="Date")

##Resumen e Histograma

summary(res)
##      Index             (Intercept)           SP.Close       
##  Min.   :2014-06-18   Min.   :-120844.4   Min.   :-10.3194  
##  1st Qu.:2015-11-13   1st Qu.: -14978.2   1st Qu.: -0.1529  
##  Median :2017-04-11   Median :   -903.8   Median :  0.8113  
##  Mean   :2017-04-11   Mean   : -10054.0   Mean   :  5.2066  
##  3rd Qu.:2018-09-06   3rd Qu.:    702.8   3rd Qu.:  7.5255  
##  Max.   :2020-01-30   Max.   :  40337.8   Max.   : 50.1830  
##  Desv  Estandar Res.
##  Min.   :  17.97    
##  1st Qu.:  65.97    
##  Median : 108.01    
##  Mean   : 673.01    
##  3rd Qu.: 997.44    
##  Max.   :3048.28
hist(res[,"SP.Close"], breaks=100, main="Histograma de los coeficientes estimados", xlab="Value")

##Coeficientes de regresión residuos

rr <- rollapply(na.approx(na.trim(tmp.ret, side="both")), width = 120,
                FUN = function(z) coef(lm(BTC.Close~ SP.Close, data = as.data.frame(z))),
                by.column = FALSE, align = "right")

rr.var <- rollapply(na.approx(na.trim(tmp.ret, side="both")), width = 120,
                    FUN = function(z) sd(residuals(lm (BTC.Close~ SP.Close, data = as.data.frame(z)))),
                    by.column = FALSE, align = "right")

res.ret <- merge(rr,rr.var)
colnames(res.ret)[3] <- "St. Dev. Resid." 
plot(res.ret, main="Coeficiente de regression de los retornos de las series.", xlab="Date")

##Resumen e Histograma

summary(res.ret)
##      Index             (Intercept)           SP.Close        St. Dev. Resid.  
##  Min.   :2014-06-19   Min.   :-0.008115   Min.   :-1.90007   Min.   :0.01588  
##  1st Qu.:2015-11-15   1st Qu.:-0.001573   1st Qu.:-0.50235   1st Qu.:0.03541  
##  Median :2017-04-11   Median : 0.002882   Median :-0.05253   Median :0.04189  
##  Mean   :2017-04-11   Mean   : 0.002795   Mean   : 0.08352   Mean   :0.04359  
##  3rd Qu.:2018-09-06   3rd Qu.: 0.006041   3rd Qu.: 0.39382   3rd Qu.:0.04975  
##  Max.   :2020-01-30   Max.   : 0.017093   Max.   : 3.41480   Max.   :0.06856
hist(res.ret[,"SP.Close"], breaks=100, main="Histograma coeficientes estimados de los retornos", xlab="Value")

##Análisis de desviación estándard

library(xts)
tail(to.yearly(apple.zoo))
##            apple.zoo.Open apple.zoo.High apple.zoo.Low apple.zoo.Close
## 2015-12-31          313.9          466.5         183.0           429.0
## 2016-12-30          432.9          981.7         358.9           959.3
## 2017-12-29         1019.3        18934.0         778.6         14317.0
## 2018-12-31        13354.0        16917.0        3282.8          3830.5
## 2019-12-31         3963.0        12876.0        3436.1          7208.3
## 2020-01-30         7212.7         9512.7        6989.4          9512.7
start(apple.zoo)
## [1] "2014-01-01"
end(apple.zoo)
## [1] "2020-01-30"
plot(apply.monthly(window(apple.zoo [,"BTC.Close"], start="2014-01-01") ,function(x) sd(x, na.rm=TRUE)), main="D.E Mensual de los Precios de Cierre de BTC 2014-20", ylab="Desviacion Estandar", xlab="Año")

plot(apply.yearly(window(apple.zoo[,"BTC.Close"], start="2014-01-01",end="2019-12-30") ,function(x) sd(x, na.rm=TRUE)), main="D.E Anual de los Precios de Cierre de BTC 2014-19", ylab="Desviacion Estandar", xlab="Año")

plot(apply.monthly(window(apple.zoo [,"SP.Close"], start="2014-01-01") ,function(x) sd(x, na.rm=TRUE)), main="D.E Mensual de los Precios de Cierre del S&P500 2014-20", ylab="Desviacion Estandar", xlab="Año")

plot(apply.yearly(window(apple.zoo[,"SP.Close"], start="2014-01-01",end="2019-12-30") ,function(x) sd(x, na.rm=TRUE)), main="D.E Anual de los Precios de Cierre del S&P500 2014-19", ylab="Desviacion Estandar", xlab="Año")

#Modelización ARIMA

library(vars)
## Loading required package: MASS
## Loading required package: strucchange
## Loading required package: sandwich
## Loading required package: urca
## Loading required package: lmtest
library(forecast)
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
## Registered S3 methods overwritten by 'forecast':
##   method             from    
##   fitted.fracdiff    fracdiff
##   residuals.fracdiff fracdiff
library(TSA)
## Registered S3 methods overwritten by 'TSA':
##   method       from    
##   fitted.Arima forecast
##   plot.Arima   forecast
## 
## Attaching package: 'TSA'
## The following objects are masked from 'package:PerformanceAnalytics':
## 
##     kurtosis, skewness
## The following objects are masked from 'package:stats':
## 
##     acf, arima
## The following object is masked from 'package:utils':
## 
##     tar
library(ggplot2)
library(tseries)
## 
## Attaching package: 'tseries'
## The following object is masked from 'package:chron':
## 
##     is.weekend

##Graficamos y aplicamos un logaritmo para suavizar los datos

apple.mod <- na.approx(na.trim(apple.zoo[,"BTC.Close"], side="both"))
head(to.daily(apple.mod))
##            apple.mod.Open apple.mod.High apple.mod.Low apple.mod.Close
## 2014-01-01          740.3          740.3         740.3           740.3
## 2014-01-02          775.0          775.0         775.0           775.0
## 2014-01-03          812.1          812.1         812.1           812.1
## 2014-01-06          934.5          934.5         934.5           934.5
## 2014-01-07          791.0          791.0         791.0           791.0
## 2014-01-08          828.5          828.5         828.5           828.5
apple.mod1 <- to.daily(apple.mod)[,"apple.mod.Close"]
start(apple.mod1)
## [1] "2014-01-01"
apple.ts <- ts(apple.mod1, start=c(2014,01,01), freq=270)
autoplot(log(apple.ts), main="Log de Los Precios de Cierre de BTC 2014-20")

#Aplicación de diferencias

ggtsdisplay(diff(log(apple.ts)))

##Pruebas de raíz unitaria

adf.test(diff(log(apple.ts)))
## Warning in adf.test(diff(log(apple.ts))): p-value smaller than printed p-value
## 
##  Augmented Dickey-Fuller Test
## 
## data:  diff(log(apple.ts))
## Dickey-Fuller = -10.811, Lag order = 11, p-value = 0.01
## alternative hypothesis: stationary
pp.test(diff(log(apple.ts), alternative="stationary"))
## Warning in pp.test(diff(log(apple.ts), alternative = "stationary")): p-value
## smaller than printed p-value
## 
##  Phillips-Perron Unit Root Test
## 
## data:  diff(log(apple.ts), alternative = "stationary")
## Dickey-Fuller Z(alpha) = -1696.1, Truncation lag parameter = 8, p-value
## = 0.01
## alternative hypothesis: stationary

##Descomposición de retornos

plot(decompose(diff(log(apple.ts))))

##Arima

arima(log(apple.ts), order = c(0,1,0))
## 
## Call:
## arima(x = log(apple.ts), order = c(0, 1, 0))
## 
## 
## sigma^2 estimated as 0.002075:  log likelihood = 2677.01,  aic = -5354.03
arima(log(apple.ts), order = c(1,1,1))
## 
## Call:
## arima(x = log(apple.ts), order = c(1, 1, 1))
## 
## Coefficients:
##          ar1      ma1
##       0.1991  -0.2177
## s.e.  0.8046   0.7909
## 
## sigma^2 estimated as 0.002074:  log likelihood = 2677.31,  aic = -5350.62

##Prueba Ljung box

tsdiag(arima(log(apple.ts), order = c(0,1,0)))

tsdiag(arima(log(apple.ts), order = c(1,1,1)))

checkresiduals(arima(log(apple.ts), order = c(0,1,0)))

## 
##  Ljung-Box test
## 
## data:  Residuals from ARIMA(0,1,0)
## Q* = 350.21, df = 321, p-value = 0.126
## 
## Model df: 0.   Total lags used: 321