library(quantmod)
## Warning: package 'quantmod' was built under R version 4.4.1
## Cargando paquete requerido: xts
## Cargando paquete requerido: zoo
## 
## Adjuntando el paquete: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## Cargando paquete requerido: TTR
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.1     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.1
## ✔ purrr     1.0.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::first()  masks xts::first()
## ✖ dplyr::lag()    masks stats::lag()
## ✖ dplyr::last()   masks xts::last()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(timeSeries)
## Cargando paquete requerido: timeDate
## 
## Adjuntando el paquete: 'timeSeries'
## 
## The following object is masked from 'package:dplyr':
## 
##     lag
## 
## The following object is masked from 'package:zoo':
## 
##     time<-
## 
## The following objects are masked from 'package:graphics':
## 
##     lines, points
library(tseries)
library(zoo)
library(xts)
library(readxl)
library(PerformanceAnalytics)
## 
## Adjuntando el paquete: 'PerformanceAnalytics'
## 
## The following objects are masked from 'package:timeDate':
## 
##     kurtosis, skewness
## 
## The following object is masked from 'package:graphics':
## 
##     legend
library(ggplot2)
library(fPortfolio)
## Warning: package 'fPortfolio' was built under R version 4.4.1
## Cargando paquete requerido: fBasics
## 
## Adjuntando el paquete: 'fBasics'
## 
## The following objects are masked from 'package:PerformanceAnalytics':
## 
##     kurtosis, skewness
## 
## The following object is masked from 'package:TTR':
## 
##     volatility
## 
## Cargando paquete requerido: fAssets
library(PortfolioAnalytics)
## Cargando paquete requerido: foreach
## 
## Adjuntando el paquete: 'foreach'
## 
## The following objects are masked from 'package:purrr':
## 
##     accumulate, when
library(copula)
## 
## Adjuntando el paquete: 'copula'
## 
## The following object is masked from 'package:fPortfolio':
## 
##     getSigma
## 
## The following object is masked from 'package:lubridate':
## 
##     interval
#install.packages("dygraphs")
library(dygraphs)
library(forecast)
## Warning: package 'forecast' was built under R version 4.4.1
library(ggplot.multistats)
## Warning: package 'ggplot.multistats' was built under R version 4.4.1
library(PerformanceAnalytics)
library(foreign)
library(ggfortify)
## Warning: package 'ggfortify' was built under R version 4.4.1
## Registered S3 methods overwritten by 'ggfortify':
##   method                 from    
##   autoplot.Arima         forecast
##   autoplot.acf           forecast
##   autoplot.ar            forecast
##   autoplot.bats          forecast
##   autoplot.decomposed.ts forecast
##   autoplot.ets           forecast
##   autoplot.forecast      forecast
##   autoplot.stl           forecast
##   autoplot.ts            forecast
##   fitted.ar              forecast
##   fortify.ts             forecast
##   residuals.ar           forecast
library(gridExtra)
## Warning: package 'gridExtra' was built under R version 4.4.1
## 
## Adjuntando el paquete: 'gridExtra'
## 
## The following object is masked from 'package:dplyr':
## 
##     combine
library(seasonal)
## Warning: package 'seasonal' was built under R version 4.4.1
## 
## Adjuntando el paquete: 'seasonal'
## 
## The following objects are masked from 'package:timeSeries':
## 
##     outlier, series
## 
## The following object is masked from 'package:tibble':
## 
##     view
#install.packages("rugarch")
library(rugarch)
## Cargando paquete requerido: parallel
## 
## Adjuntando el paquete: 'rugarch'
## 
## The following objects are masked from 'package:fBasics':
## 
##     qgh, qnig
## 
## The following object is masked from 'package:purrr':
## 
##     reduce
## 
## The following object is masked from 'package:stats':
## 
##     sigma
library(ggplot2)
library(readxl)
library(tseries)
library(forecast)
library(ggplot.multistats)
library(PerformanceAnalytics)
library(foreign)
library(ggfortify)
library(gridExtra)
library(seasonal)
library(lattice)
library(zoo)
library(urca)
## Warning: package 'urca' was built under R version 4.4.1
library(dynlm)
## Warning: package 'dynlm' was built under R version 4.4.1
# Define el nuevo portafolio
cartera <- c("PM","NEM","KR", "PFE","AMZN","XOM","WMT","PG","CL","IBM")
Precios_i <- NULL
for (Cabecera_i in cartera)
  Precios_i <- cbind(Precios_i, getSymbols(Cabecera_i, from = "2010-01-01",to="2024-05-31", auto.assign = FALSE)[, 6])
# Renombra las columnas con los nombres de las acciones
colnames(Precios_i) <- cartera
Retorno_i <- na.omit(Return.calculate(Precios_i,method = "log")) # Calculamos retornos mediante logaritmos
RetPort_i <- as.timeSeries(Retorno_i) # #Convertimos los retornos en series de tiempo
colnames(Retorno_i) <- c("PM","NEM","KR", "PFE","AMZN","XOM","WMT","PG","CL","IBM")
peso_i <-c(0.0612,0.0751,0.0898,0.1168,0.0314,0.0498,0.1868,0.1966,0.1327,0.0598)
Retorno_portafolio_i <- as.numeric(peso_i%*%t(Retorno_i))

Retorno_portafolio_i <- xts(Retorno_portafolio_i,order.by = index(Retorno_i))
names(Retorno_portafolio_i)<- c("Retorno del Portafolio")
ggplot(data = Retorno_portafolio_i, aes(x = index(Retorno_portafolio_i))) +
   geom_line(aes(y = `Retorno del Portafolio`, color = "Retorno del Portafolio")) +
  labs(x = "Periodos", y = "Retornos", color = "Acción") +
  scale_color_manual(values = c("Retorno del Portafolio" = "slategray3")) +
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.6),  # Centrar el título
  ) +
  ggtitle("Retornos del Portafolio")

#Portafolio con pesos iguales 
peso_i <-c(0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1)
Retorno_portafolio_iguales <- as.numeric(peso_i%*%t(Retorno_i))

Retorno_portafolio_iguales <- xts(Retorno_portafolio_iguales,order.by = index(Retorno_i))
names(Retorno_portafolio_iguales)<- c("Retorno del Portafolio con Pesos Iguales")
ggplot(data = Retorno_portafolio_iguales, aes(x = index(Retorno_portafolio_iguales))) +
   geom_line(aes(y = Retorno_portafolio_iguales$`Retorno del Portafolio con Pesos Iguales`, color = "Portafolio")) +
  labs(x = "Periodos", y = "Retornos", color = "Acción") +
  scale_color_manual(values = c("Portafolio" = "#11FFF4")) +
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.5),  # Centrar el título
  ) +
  ggtitle("Retornos del Portafolio con Pesos Iguales")
## Don't know how to automatically pick scale for object of type <xts/zoo>.
## Defaulting to continuous.

#--------------------------------------------------------------------
mean_portafolio_igual <- mean(Retorno_portafolio_iguales)
sd_portafolio_igual <- sd(Retorno_portafolio_iguales)
cat("Media:", mean_portafolio_igual, "\n")
## Media: 0.000377742
cat("Desviación Estándar:", sd_portafolio_igual, "\n")
## Desviación Estándar: 0.008782236
#ESTIMACION DE LOS MODELOS NO LINEALES TAR, SETAR, STAR y Modelo de Markov Switching del
#Retorno del Portafolio de minima varianza.
#install.packages(c("TSA", "tsDyn", "MSwM"))
#install.packages("mrstar")
#library(mrstar)
library(TSA)
## Warning: package 'TSA' was built under R version 4.4.1
## Registered S3 methods overwritten by 'TSA':
##   method       from    
##   fitted.Arima forecast
##   plot.Arima   forecast
## 
## Adjuntando el paquete: 'TSA'
## The following objects are masked from 'package:fBasics':
## 
##     kurtosis, skewness
## The following objects are masked from 'package:PerformanceAnalytics':
## 
##     kurtosis, skewness
## The following objects are masked from 'package:timeDate':
## 
##     kurtosis, skewness
## The following object is masked from 'package:readr':
## 
##     spec
## The following objects are masked from 'package:stats':
## 
##     acf, arima
## The following object is masked from 'package:utils':
## 
##     tar
library(tsDyn)
## Warning: package 'tsDyn' was built under R version 4.4.1
library(MSwM)
## Warning: package 'MSwM' was built under R version 4.4.1
# Ajustar el modelo TAR

tar_model <- setar(Retorno_portafolio_i, m = 2, thDelay = 1, trim = 0.1, model = "TAR")
summary(tar_model)
## 
## Non linear autoregressive model
## 
## SETAR model ( 2 regimes)
## Coefficients:
## Low regime:
##      const.L       phiL.1       phiL.2 
##  0.001222685 -0.242885314  0.032053988 
## 
## High regime:
##       const.H        phiH.1        phiH.2 
##  0.0002197447 -0.0247513436  0.0550748846 
## 
## Threshold:
## -Variable: Z(t) = + (0) X(t)+ (1)X(t-1)
## -Value: -0.007886
## Proportion of points in low regime: 11.7%     High regime: 88.3% 
## 
## Residuals:
##         Min          1Q      Median          3Q         Max 
## -0.08723346 -0.00399807  0.00018547  0.00447199  0.08293141 
## 
## Fit:
## residuals variance = 7.032e-05,  AIC = -34650, MAPE = 357.5%
## 
## Coefficient(s):
## 
##            Estimate  Std. Error  t value  Pr(>|t|)    
## const.L  0.00122269  0.00083830   1.4585    0.1448    
## phiL.1  -0.24288531  0.03028417  -8.0202 1.413e-15 ***
## phiL.2   0.03205399  0.05211167   0.6151    0.5385    
## const.H  0.00021974  0.00015777   1.3928    0.1638    
## phiH.1  -0.02475134  0.01976100  -1.2525    0.2105    
## phiH.2   0.05507488  0.02310629   2.3835    0.0172 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Threshold
## Variable: Z(t) = + (0) X(t) + (1) X(t-1)
## 
## Value: -0.007886
# Ajustar el modelo SETAR
setar_model <- setar(Retorno_portafolio_i, m=2, thDelay=1)
summary(setar_model)
## 
## Non linear autoregressive model
## 
## SETAR model ( 2 regimes)
## Coefficients:
## Low regime:
##       const.L        phiL.1        phiL.2 
##  0.0009257229 -0.2070494750  0.0234854716 
## 
## High regime:
##       const.H        phiH.1        phiH.2 
##  0.0001324254 -0.0210747754  0.0675743466 
## 
## Threshold:
## -Variable: Z(t) = + (0) X(t)+ (1)X(t-1)
## -Value: -0.005496
## Proportion of points in low regime: 17.75%    High regime: 82.25% 
## 
## Residuals:
##         Min          1Q      Median          3Q         Max 
## -0.08733226 -0.00402851  0.00019088  0.00453013  0.08239812 
## 
## Fit:
## residuals variance = 7.045e-05,  AIC = -34643, MAPE = 379.5%
## 
## Coefficient(s):
## 
##            Estimate  Std. Error  t value  Pr(>|t|)    
## const.L  0.00092572  0.00061949   1.4943  0.135176    
## phiL.1  -0.20704947  0.02742111  -7.5507 5.447e-14 ***
## phiL.2   0.02348547  0.04546000   0.5166  0.605454    
## const.H  0.00013243  0.00017093   0.7747  0.438549    
## phiH.1  -0.02107478  0.02082221  -1.0121  0.311544    
## phiH.2   0.06757435  0.02498748   2.7043  0.006876 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Threshold
## Variable: Z(t) = + (0) X(t) + (1) X(t-1)
## 
## Value: -0.005496
# Ajustar el modelo STAR
star_model <- lstar(Retorno_portafolio_i, m=2,steps = 1, thDelay=1, trace = TRUE)
## Using maximum autoregressive order for low regime: mL = 2 
## Using maximum autoregressive order for high regime: mH = 2 
## Performing grid search for starting values...
## Starting values fixed: gamma =  41.61538 , th =  -0.008876243 ; SSE =  0.2508577 
## Optimization algorithm converged
## Optimized values fixed for regime 2  : gamma =  41.61539 , th =  -0.07661486 ; SSE =  -0.8524603
summary(star_model)
## 
## Non linear autoregressive model
## 
## LSTAR model
## Coefficients:
## Low regime:
##    const.L     phiL.1     phiL.2 
##  0.2202097 -1.9361530  1.9513001 
## 
## High regime:
##    const.H     phiH.1     phiH.2 
## -0.2291959  1.9910027 -1.6262140 
## 
## Smoothing parameter: gamma = 41.62 
## 
## Threshold
## Variable: Z(t) = + (0) X(t) + (1) X(t-1)
## 
## Value: -0.07661 
## 
## Residuals:
##         Min          1Q      Median          3Q         Max 
## -0.08634338 -0.00395042  0.00028234  0.00448395  0.07761158 
## 
## Fit:
## residuals variance = 6.843e-05,  AIC = -34747, MAPE = 379.3%
## 
## Coefficient(s):
##          Estimate  Std. Error  t value  Pr(>|z|)    
## const.L  0.220210    0.201837   1.0910 0.2752616    
## phiL.1  -1.936153    0.168405 -11.4970 < 2.2e-16 ***
## phiL.2   1.951300    1.702487   1.1461 0.2517343    
## const.H -0.229196    0.215251  -1.0648 0.2869746    
## phiH.1   1.991003    0.372216   5.3491 8.841e-08 ***
## phiH.2  -1.626214    1.414243  -1.1499 0.2501920    
## gamma   41.615386   11.601404   3.5871 0.0003344 ***
## th      -0.076615    0.017455  -4.3893 1.137e-05 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Non-linearity test of full-order LSTAR model against full-order AR model
##  F = 34.038 ; p-value = 2.2632e-15 
## 
## Threshold 
## Variable: Z(t) = + (0) X(t) + (1) X(t-1)
# Ajustar el modelo de Cambio de Régimen de Markov
mod <- lm(Retorno_portafolio_i ~ lag(Retorno_portafolio_i, -1))
msm_model <- msmFit(mod, k = 2, sw = c(TRUE,TRUE,TRUE))
summary(msm_model)
## Markov Switching Model
## 
## Call: msmFit(object = mod, k = 2, sw = c(TRUE, TRUE, TRUE))
## 
##         AIC       BIC   logLik
##   -25291.75 -25234.18 12649.87
## 
## Coefficients:
## 
## Regime 1 
## ---------
##                                  Estimate Std. Error t value  Pr(>|t|)    
## (Intercept)(S)                    -0.0011     0.0008 -1.3750 0.1691314    
## lag(Retorno_portafolio_i, -1)(S)  -0.1541     0.0458 -3.3646 0.0007665 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.01649121
## Multiple R-squared: 0.02269
## 
## Standardized Residuals:
##           Min            Q1           Med            Q3           Max 
## -7.231060e-02 -1.697820e-04  8.766519e-05  4.295236e-04  8.646552e-02 
## 
## Regime 2 
## ---------
##                                  Estimate Std. Error t value  Pr(>|t|)    
## (Intercept)(S)                     0.0006     0.0001  6.0000 1.973e-09 ***
## lag(Retorno_portafolio_i, -1)(S)  -0.0354     0.0190 -1.8632   0.06243 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.006165375
## Multiple R-squared: 0.001324
## 
## Standardized Residuals:
##           Min            Q1           Med            Q3           Max 
## -0.0187846640 -0.0033700469 -0.0000130112  0.0034884972  0.0187803078 
## 
## Transition probabilities:
##            Regime 1   Regime 2
## Regime 1 0.92171466 0.01263725
## Regime 2 0.07828534 0.98736275
plot(tar_model)

plot(setar_model)

plot(star_model)

par(mar=c(3,3,3,3))
plotProb(msm_model, which=1)

plotProb(msm_model, which=2)

plotDiag(msm_model, regime=1, which=1)

plotDiag(msm_model, regime=1, which=2)

plotDiag(msm_model, regime=1, which=3)

plotProb(msm_model, which=3)

plot(msm_model)

AIC(tar_model)
## [1] -34649.86
AIC(setar_model)
## [1] -34643.41
AIC(star_model)
## [1] -34746.74
AIC(msm_model)
## [1] -25287.75
#---------------------
BIC(tar_model)
## [1] -34606.5
BIC(setar_model)
## [1] -34600.04
BIC(star_model)
## [1] -34697.17
#BIC(msm_model)
#ESTIMACION DE LOS MODELOS NO LINEALES TAR, SETAR, STAR y Modelo de Markov Switching del
#Retorno del Portafolio de Pesos Iguales.
#install.packages(c("TSA", "tsDyn", "MSwM"))

# Ajustar el modelo TAR
tar_model_i <- setar(Retorno_portafolio_iguales, m = 2, thDelay = 1, trim = 0.1, model = "TAR")
summary(tar_model_i)
## 
## Non linear autoregressive model
## 
## SETAR model ( 2 regimes)
## Coefficients:
## Low regime:
##      const.L       phiL.1       phiL.2 
##  0.002884967 -0.237233034  0.132927059 
## 
## High regime:
##       const.H        phiH.1        phiH.2 
##  0.0002575588 -0.0239210353  0.0534432117 
## 
## Threshold:
## -Variable: Z(t) = + (0) X(t)+ (1)X(t-1)
## -Value: -0.009195
## Proportion of points in low regime: 9.99%     High regime: 90.01% 
## 
## Residuals:
##         Min          1Q      Median          3Q         Max 
## -0.08906605 -0.00425449  0.00036649  0.00460666  0.07770229 
## 
## Fit:
## residuals variance = 7.56e-05,  AIC = -34388, MAPE = 144.9%
## 
## Coefficient(s):
## 
##            Estimate  Std. Error  t value  Pr(>|t|)    
## const.L  0.00288497  0.00096361   2.9939  0.002773 ** 
## phiL.1  -0.23723303  0.03226452  -7.3528 2.389e-13 ***
## phiL.2   0.13292706  0.05384023   2.4689  0.013598 *  
## const.H  0.00025756  0.00016044   1.6054  0.108499    
## phiH.1  -0.02392104  0.01924399  -1.2430  0.213934    
## phiH.2   0.05344321  0.02271903   2.3524  0.018708 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Threshold
## Variable: Z(t) = + (0) X(t) + (1) X(t-1)
## 
## Value: -0.009195
# Ajustar el modelo SETAR
setar_model_i <- setar(Retorno_portafolio_iguales, m=2, thDelay=1)
summary(setar_model_i)
## 
## Non linear autoregressive model
## 
## SETAR model ( 2 regimes)
## Coefficients:
## Low regime:
##      const.L       phiL.1       phiL.2 
##  0.001969767 -0.207054660  0.101077577 
## 
## High regime:
##       const.H        phiH.1        phiH.2 
##  0.0001602632 -0.0167137786  0.0678435545 
## 
## Threshold:
## -Variable: Z(t) = + (0) X(t)+ (1)X(t-1)
## -Value: -0.006659
## Proportion of points in low regime: 15.62%    High regime: 84.38% 
## 
## Residuals:
##         Min          1Q      Median          3Q         Max 
## -0.08907846 -0.00430010  0.00038814  0.00462364  0.07748062 
## 
## Fit:
## residuals variance = 7.567e-05,  AIC = -34384, MAPE = 148%
## 
## Coefficient(s):
## 
##            Estimate  Std. Error  t value Pr(>|t|)    
## const.L  0.00196977  0.00070944   2.7765 0.005523 ** 
## phiL.1  -0.20705466  0.02909570  -7.1163 1.33e-12 ***
## phiL.2   0.10107758  0.04703699   2.1489 0.031709 *  
## const.H  0.00016026  0.00017293   0.9268 0.354117    
## phiH.1  -0.01671378  0.02014409  -0.8297 0.406757    
## phiH.2   0.06784355  0.02471327   2.7452 0.006077 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Threshold
## Variable: Z(t) = + (0) X(t) + (1) X(t-1)
## 
## Value: -0.006659
# Ajustar el modelo STAR
star_model_i <- lstar(Retorno_portafolio_iguales, m=2, thDelay=1,trace = TRUE)
## Using maximum autoregressive order for low regime: mL = 2 
## Using maximum autoregressive order for high regime: mH = 2 
## Performing grid search for starting values...
## Starting values fixed: gamma =  41.61538 , th =  -0.009165186 ; SSE =  0.2688339 
## Optimization algorithm converged
## Optimized values fixed for regime 2  : gamma =  41.61539 , th =  -0.06347237 ; SSE =  0.2671526
summary(star_model_i)
## Warning in vcov.lstar(object): Hessian negative-semi definite
## Warning in sqrt(diag(vc)): Se han producido NaNs
## 
## Non linear autoregressive model
## 
## LSTAR model
## Coefficients:
## Low regime:
##    const.L     phiL.1     phiL.2 
##  0.1688292 -1.4183783  1.9368088 
## 
## High regime:
##    const.H     phiH.1     phiH.2 
## -0.1807432  1.4978238 -1.5526125 
## 
## Smoothing parameter: gamma = 41.62 
## 
## Threshold
## Variable: Z(t) = + (0) X(t) + (1) X(t-1)
## 
## Value: -0.06347 
## 
## Residuals:
##         Min          1Q      Median          3Q         Max 
## -0.08800104 -0.00420335  0.00041312  0.00462213  0.07591407 
## 
## Fit:
## residuals variance = 7.37e-05,  AIC = -34478, MAPE = 136.1%
## 
## Coefficient(s):
##          Estimate  Std. Error  t value  Pr(>|z|)    
## const.L  0.168829         NaN      NaN       NaN    
## phiL.1  -1.418378    0.126803  -11.186 < 2.2e-16 ***
## phiL.2   1.936809         NaN      NaN       NaN    
## const.H -0.180743         NaN      NaN       NaN    
## phiH.1   1.497824    0.083439   17.951 < 2.2e-16 ***
## phiH.2  -1.552613         NaN      NaN       NaN    
## gamma   41.615385         NaN      NaN       NaN    
## th      -0.063472         NaN      NaN       NaN    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Non-linearity test of full-order LSTAR model against full-order AR model
##  F = 32.095 ; p-value = 1.5258e-14 
## 
## Threshold 
## Variable: Z(t) = + (0) X(t) + (1) X(t-1)
# Ajustar el modelo de Cambio de Régimen de Markov
mod_i <- lm(Retorno_portafolio_iguales ~ lag(Retorno_portafolio_iguales, -1))
msm_model_i <- msmFit(mod_i, k = 2, sw = c(TRUE, TRUE, TRUE))
summary(msm_model_i)
## Markov Switching Model
## 
## Call: msmFit(object = mod_i, k = 2, sw = c(TRUE, TRUE, TRUE))
## 
##         AIC       BIC   logLik
##   -25022.14 -24964.58 12515.07
## 
## Coefficients:
## 
## Regime 1 
## ---------
##                                        Estimate Std. Error t value Pr(>|t|)   
## (Intercept)(S)                          -0.0011     0.0007 -1.5714 0.116090   
## lag(Retorno_portafolio_iguales, -1)(S)  -0.1317     0.0408 -3.2279 0.001247 **
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.01575909
## Multiple R-squared: 0.01685
## 
## Standardized Residuals:
##           Min            Q1           Med            Q3           Max 
## -7.745831e-02 -1.883186e-04  8.387469e-05  4.629094e-04  7.909368e-02 
## 
## Regime 2 
## ---------
##                                        Estimate Std. Error t value Pr(>|t|)    
## (Intercept)(S)                           0.0007     0.0001  7.0000 2.56e-12 ***
## lag(Retorno_portafolio_iguales, -1)(S)  -0.0348     0.0199 -1.7487  0.08034 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.006271084
## Multiple R-squared: 0.001268
## 
## Standardized Residuals:
##           Min            Q1           Med            Q3           Max 
## -1.994376e-02 -3.328413e-03  3.271578e-08  3.341198e-03  1.978669e-02 
## 
## Transition probabilities:
##            Regime 1   Regime 2
## Regime 1 0.94703814 0.01121435
## Regime 2 0.05296186 0.98878565
plot(tar_model_i)

plot(setar_model_i)

plot(star_model_i)

par(mar=c(3,3,3,3))
plotProb(msm_model_i, which=1)

plotProb(msm_model_i, which=2)

plotDiag(msm_model_i, regime=1, which=1)

plotDiag(msm_model_i, regime=1, which=2)

plotDiag(msm_model_i, regime=1, which=3)

plotProb(msm_model_i, which=3)

plot(msm_model_i)

AIC(tar_model_i)
## [1] -34387.66
AIC(setar_model_i)
## [1] -34384.11
AIC(star_model_i)
## [1] -34477.85
AIC(msm_model_i)
## [1] -25018.14
#---------------------
BIC(tar_model_i)
## [1] -34344.29
BIC(setar_model_i)
## [1] -34340.74
BIC(star_model_i)
## [1] -34428.29
#BIC(msm_model_i)
#-----------------------------------------------------------------------------------------------------------------
#--------------APLICACION DE LOS MODELOS NO LINEALES A LOS PRECIOS DE LA ACCION DE PM ----------------------------
#-----------------------------------------------------------------------------------------------------------------
PM <- c("PM")
Precios_PM <- NULL
for (Cabecera_PM in PM)
  Precios_PM <- cbind(Precios_PM, getSymbols(Cabecera_PM, from = "2023-01-01",to="2024-05-31", auto.assign = FALSE)[, 6])
# Renombra las columnas con los nombres de las acciones
colnames(Precios_PM) <- PM
dygraph(Precios_PM,main = "Precio de la Accion ",ylab = "Precio Ajustado",xlab = "Periodo") %>% dyRangeSelector()
# Ajustar el modelo TAR
tar_model_pm <- setar(Precios_PM, m = 2, thDelay = 1, trim = 0.1, model = "TAR")
## Warning: Possible unit root in the high regime. Roots are: 0.939 4.0577
summary(tar_model_pm)
## 
## Non linear autoregressive model
## 
## SETAR model ( 2 regimes)
## Coefficients:
## Low regime:
##     const.L      phiL.1      phiL.2 
##  2.65861474  1.03180727 -0.06100659 
## 
## High regime:
##    const.H     phiH.1     phiH.2 
## -8.0270815  0.8185734  0.2624684 
## 
## Threshold:
## -Variable: Z(t) = + (0) X(t)+ (1)X(t-1)
## -Value: 92.68
## Proportion of points in low regime: 84.94%    High regime: 15.06% 
## 
## Residuals:
##       Min        1Q    Median        3Q       Max 
## -3.968210 -0.561759 -0.011703  0.528850  3.519580 
## 
## Fit:
## residuals variance = 0.83,  AIC = -52, MAPE = 0.7815%
## 
## Coefficient(s):
## 
##          Estimate  Std. Error  t value  Pr(>|t|)    
## const.L  2.658615    2.088844   1.2728   0.20395    
## phiL.1   1.031807    0.059436  17.3600 < 2.2e-16 ***
## phiL.2  -0.061007    0.062066  -0.9829   0.32632    
## const.H -8.027081    6.581935  -1.2196   0.22346    
## phiH.1   0.818573    0.119572   6.8459 3.446e-11 ***
## phiH.2   0.262468    0.142362   1.8437   0.06608 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Threshold
## Variable: Z(t) = + (0) X(t) + (1) X(t-1)
## 
## Value: 92.68
# Ajustar el modelo SETAR
setar_model_pm <- setar(Precios_PM, m=2, thDelay=1)
summary(setar_model_pm)
## 
## Non linear autoregressive model
## 
## SETAR model ( 2 regimes)
## Coefficients:
## Low regime:
##   const.L    phiL.1    phiL.2 
## 3.4177523 0.7849597 0.1787806 
## 
## High regime:
##     const.H      phiH.1      phiH.2 
##  1.75283877  1.04561098 -0.06550739 
## 
## Threshold:
## -Variable: Z(t) = + (0) X(t)+ (1)X(t-1)
## -Value: 87.25
## Proportion of points in low regime: 21.59%    High regime: 78.41% 
## 
## Residuals:
##       Min        1Q    Median        3Q       Max 
## -4.333270 -0.548468  0.016512  0.524379  3.569873 
## 
## Fit:
## residuals variance = 0.8313,  AIC = -51, MAPE = 0.7792%
## 
## Coefficient(s):
## 
##          Estimate  Std. Error  t value  Pr(>|t|)    
## const.L  3.417752    8.406634   0.4066    0.6846    
## phiL.1   0.784960    0.120118   6.5349 2.265e-10 ***
## phiL.2   0.178781    0.142403   1.2555    0.2102    
## const.H  1.752839    1.959415   0.8946    0.3716    
## phiH.1   1.045611    0.059416  17.5981 < 2.2e-16 ***
## phiH.2  -0.065507    0.061861  -1.0589    0.2904    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Threshold
## Variable: Z(t) = + (0) X(t) + (1) X(t-1)
## 
## Value: 87.25
# Ajustar el modelo STAR
star_model_pm <- lstar(Precios_PM, m=2,steps = 1, thDelay=1,trace = TRUE)
## Using maximum autoregressive order for low regime: mL = 2 
## Using maximum autoregressive order for high regime: mH = 2 
## Performing grid search for starting values...
## Starting values fixed: gamma =  100 , th =  92.70527 ; SSE =  294.254 
## Grid search selected lower/upper bound gamma (was:  1 100 ]). 
##                    Might try to widen bound with arg: 'starting.control=list(gammaInt=c(1,200))'
## Optimization algorithm converged
## Optimized values fixed for regime 2  : gamma =  100.0007 , th =  92.70195 ; SSE =  294.2382
summary(star_model_pm)
## 
## Non linear autoregressive model
## 
## LSTAR model
## Coefficients:
## Low regime:
##     const.L      phiL.1      phiL.2 
##  2.74101231  1.03169360 -0.06183473 
## 
## High regime:
##     const.H      phiH.1      phiH.2 
## -10.5067511  -0.2130023   0.3214743 
## 
## Smoothing parameter: gamma = 100 
## 
## Threshold
## Variable: Z(t) = + (0) X(t) + (1) X(t-1)
## 
## Value: 92.7 
## 
## Residuals:
##        Min         1Q     Median         3Q        Max 
## -3.9757000 -0.5578334 -0.0095117  0.5221244  3.5234265 
## 
## Fit:
## residuals variance = 0.8312,  AIC = -49, MAPE = 0.7826%
## 
## Coefficient(s):
##           Estimate  Std. Error   t value Pr(>|z|)    
## const.L   2.741012    2.083541    1.3156  0.18832    
## phiL.1    1.031694    0.059005   17.4847  < 2e-16 ***
## phiL.2   -0.061835    0.061627   -1.0034  0.31568    
## const.H -10.506751    6.938040   -1.5144  0.12993    
## phiH.1   -0.213002    0.134452   -1.5842  0.11314    
## phiH.2    0.321474    0.157131    2.0459  0.04077 *  
## gamma   100.000715  117.572233    0.8505  0.39502    
## th       92.701949    0.024361 3805.2696  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Non-linearity test of full-order LSTAR model against full-order AR model
##  F = 0.47338 ; p-value = 0.62329 
## 
## Threshold 
## Variable: Z(t) = + (0) X(t) + (1) X(t-1)
# Ajustar el modelo de Cambio de Régimen de Markov
mod_pm <- lm(Precios_PM ~ lag(Precios_PM, -1))
msm_model_pm <- msmFit(mod_pm, k = 2, sw = c(TRUE, TRUE,TRUE))
summary(msm_model_pm)
## Markov Switching Model
## 
## Call: msmFit(object = mod_pm, k = 2, sw = c(TRUE, TRUE, TRUE))
## 
##        AIC      BIC  logLik
##   931.8599 970.7917 -461.93
## 
## Coefficients:
## 
## Regime 1 
## ---------
##                        Estimate Std. Error t value Pr(>|t|)    
## (Intercept)(S)           6.9012     8.8572  0.7792   0.4359    
## lag(Precios_PM, -1)(S)   0.9230     0.0976  9.4570   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.324246
## Multiple R-squared: 0.8355
## 
## Standardized Residuals:
##         Min          Q1         Med          Q3         Max 
## -3.07663523 -0.22617953 -0.01568988  0.22841093  4.41334362 
## 
## Regime 2 
## ---------
##                        Estimate Std. Error t value Pr(>|t|)    
## (Intercept)(S)           3.5767     2.6752   1.337   0.1812    
## lag(Precios_PM, -1)(S)   0.9599     0.0294  32.650   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.7127481
## Multiple R-squared: 0.9457
## 
## Standardized Residuals:
##          Min           Q1          Med           Q3          Max 
## -1.227027742 -0.471963274 -0.009326425  0.497600194  1.289352030 
## 
## Transition probabilities:
##           Regime 1  Regime 2
## Regime 1 0.4875134 0.1812671
## Regime 2 0.5124866 0.8187329
plot(tar_model_pm)

plot(setar_model_pm)

plot(star_model_pm)

par(mar=c(3,3,3,3))
plotProb(msm_model_pm, which=1)

plotProb(msm_model_pm, which=2)

plotDiag(msm_model_pm, regime=1, which=1)

plotDiag(msm_model_pm, regime=1, which=2)

plotDiag(msm_model_pm, regime=1, which=3)

plotProb(msm_model_pm, which=3)

plotDiag(msm_model_pm, regime=2, which=1)

plotDiag(msm_model_pm, regime=2, which=2)

plotDiag(msm_model_pm, regime=2, which=3)

plot(msm_model_pm)

AIC(tar_model_pm)
## [1] -51.95331
AIC(setar_model_pm)
## [1] -51.40942
AIC(star_model_pm)
## [1] -49.45712
AIC(msm_model_pm)
## [1] 935.8599
#---------------------
BIC(tar_model_pm)
## [1] -24.86823
BIC(setar_model_pm)
## [1] -24.32434
BIC(star_model_pm)
## [1] -18.50275
#BIC(msm_model_i)