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
#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(readxl)
library(tseries)
library(forecast)
library(ggplot.multistats)
library(PerformanceAnalytics)
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
#install.packages("sde")
library(sde)
## Warning: package 'sde' was built under R version 4.4.2
## Cargando paquete requerido: MASS
## 
## Adjuntando el paquete: 'MASS'
## 
## The following object is masked from 'package:dplyr':
## 
##     select
## 
## Cargando paquete requerido: stats4
## Cargando paquete requerido: fda
## Warning: package 'fda' was built under R version 4.4.2
## Cargando paquete requerido: splines
## Cargando paquete requerido: fds
## Warning: package 'fds' was built under R version 4.4.2
## Cargando paquete requerido: rainbow
## Warning: package 'rainbow' was built under R version 4.4.2
## Cargando paquete requerido: pcaPP
## Cargando paquete requerido: RCurl
## 
## Adjuntando el paquete: 'RCurl'
## 
## The following object is masked from 'package:tidyr':
## 
##     complete
## 
## Cargando paquete requerido: deSolve
## Warning: package 'deSolve' was built under R version 4.4.1
## 
## Adjuntando el paquete: 'deSolve'
## 
## The following object is masked from 'package:fBasics':
## 
##     rk
## 
## 
## Adjuntando el paquete: 'fda'
## 
## The following object is masked from 'package:lattice':
## 
##     melanoma
## 
## The following object is masked from 'package:forecast':
## 
##     fourier
## 
## The following object is masked from 'package:graphics':
## 
##     matplot
## 
## sde 2.0.18
## Companion package to the book
## 'Simulation and Inference for Stochastic Differential Equations With R Examples'
## Iacus, Springer NY, (2008)
## To check the errata corrige of the book, type vignette("sde.errata")
# 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
dygraph(Precios_i,main = "Precios de las Acciones",ylab = "Precio Ajustado",xlab = "Periodo") %>% dyRangeSelector()
# Gráfico de Precios
ggplot(data = Precios_i, aes(x = index(Precios_i))) +
  geom_line(aes(y = PM, color = "PM")) +
  geom_line(aes(y = NEM, color = "NEM")) +
  geom_line(aes(y = KR, color = "KR")) +
  geom_line(aes(y = PFE, color = "PFE")) +
  geom_line(aes(y = AMZN, color = "AMZN")) +
  geom_line(aes(y = XOM, color = "XOM")) +
  geom_line(aes(y = WMT, color = "WMT")) +
  geom_line(aes(y = PG, color = "PG")) +
  geom_line(aes(y = CL, color = "CL")) +
  geom_line(aes(y = IBM, color = "IBM")) +
  labs(x = "Periodos", y = "Precio Ajustado", color = "Acción") +
  scale_color_manual(values = c("PM" = "#CD5B45", "NEM" = "#458B74","KR"="#CB977C","PFE"="#C41028","AMZN"="#3F0A18","XOM"="#A06444","WMT"="#8A1DC0",
                                "PG"="#9D8E8E","CL"="#11FFF4","IBM"="slategray3")) +
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.6),  # Centrar el título
  ) +
  ggtitle("Precios de las accciones")

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")
#Retornos del Portafolio por medio del metodo de la Minima Varianza
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 de Minima Varianza")

#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.

tail(Retorno_portafolio_i)
##            Retorno del Portafolio
## 2024-05-22           0.0003972786
## 2024-05-23          -0.0152477702
## 2024-05-24           0.0024902356
## 2024-05-28          -0.0078500210
## 2024-05-29          -0.0088960814
## 2024-05-30           0.0017678418
length(Retorno_portafolio_i)
## [1] 3625
sesgo <- skewness(Retorno_portafolio_i)
sesgo
## [1] -0.192377
## attr(,"method")
## [1] "moment"
kurtosis(Retorno_portafolio_i)
## [1] 11.55343
## attr(,"method")
## [1] "excess"
#hist(Retorno_portafolio_i)
summary(Retorno_portafolio_i)
##      Index            Retorno del Portafolio
##  Min.   :2010-01-05   Min.   :-0.0838585    
##  1st Qu.:2013-08-12   1st Qu.:-0.0036426    
##  Median :2017-03-17   Median : 0.0005119    
##  Mean   :2017-03-17   Mean   : 0.0003616    
##  3rd Qu.:2020-10-21   3rd Qu.: 0.0047479    
##  Max.   :2024-05-30   Max.   : 0.0884195
#MOVIMIENTO GEOMETRICO ESTANDAR O PROCESO DE WEINER PARA EL PROTAFOLIO DE MINIMA 
#VARINANZA
# Definir parámetros
set.seed(123)  # Para reproducibilidad
n <- 1000  # Número de pasos
T <- 365  # Tiempo total
dt <- T/n  # Incremento de tiempo

# Generar el proceso de Wiener
W <- c(0, cumsum(rnorm(n, mean = mean(Retorno_portafolio_i), sd = sd(Retorno_portafolio_i))))

# Crear un data frame para graficar
data <- data.frame(Time = 0:n * dt, Wiener_Process = W)
# Graficar el proceso de Wiener
ggplot(data, aes(x = Time, y = Wiener_Process)) +
  geom_line(color = "blue") +
  labs(title = "Simulación del Proceso de Wiener del portafolio 1",
       x = "Tiempo",
       y = "Valor del Proceso")

#SIMULACION POR EL MOVIMIENTO BROWNIANO Geometrico
t<-365
tseq<- 1:t
dt <- 1/t
muC<-mean(Retorno_portafolio_i)
sC<-sd(Retorno_portafolio_i)
P0<- 1.767848e-03
x <- P0
nsim<- 1000
m<- matrix(ncol = nsim, nrow = t)
for (i in 1:nsim) {
  m[1,i] <- P0
  for (h in 2:t) {
    e <- rnorm(1)
    m[h, i]<- m[(h-1),i]*exp((muC-(sC^2)/2)*dt+sC*e*sqrt(dt))
  }
}

gbm_df <- as.data.frame(m) %>%
  mutate(tiempo = 1:nrow(m)) %>%
  pivot_longer(-tiempo, names_to = 'sim', values_to = 'Retorno')

gbm_df %>%
  ggplot(aes(x=tiempo, y=Retorno, color=sim)) +
  geom_line() +
  theme(legend.position = 'none')

#-------------------------------------------------------------------------
m2<-t(m)
plot(tseq, m2[1, ],xlab = "Tiempo", ylab = "Retornos", type = "l",ylim = c(min(m2[1, ])/1.1,max(m2[1, ])*1.1))
apply(m2[2:nsim, ],MARGIN =  1, function(x, r){
  lines(tseq, x)
})

## NULL
#GRAFICO DE LAS PROYECCIONES
proyeccion1=matrix(nrow =(3625+364),ncol = 1 )
proyeccion1[1:3625]=Retorno_portafolio_i
matplot(proyeccion1,type="l",ylim=c(-0.05,0.05))
proyeccion2=matrix(nrow = (3625+364),ncol = nsim)
proyeccion2[3625:3989,]=m
matlines(proyeccion2,type = "l")

#intervalos de confianza
alfa=0.05
q1=quantile(m[t,],(alfa/2))
q2=quantile(m[t,],(1-alfa/2))
#------------------------------------
#Distribucion de los retornos futuros 
plot(density(m[t,]),ylab="",xlab="",
     main="Empirical Distribution",lwd=3)
abline(h=NULL,v=q1,col="blue",lwd=2)
abline(h=NULL,v=q2,col="green",lwd=2)

#Probabilidad de que los retornos en 364 dias sean menores que el retorno inicial 
m_t=m[t,]
m_t[m_t<1.767848e-03]
##   [1] 0.001746777 0.001765441 0.001759898 0.001763960 0.001750397 0.001746442
##   [7] 0.001765747 0.001762429 0.001760475 0.001760948 0.001748539 0.001749353
##  [13] 0.001756975 0.001766506 0.001750580 0.001743899 0.001754995 0.001742595
##  [19] 0.001763741 0.001753584 0.001745634 0.001758457 0.001763366 0.001760490
##  [25] 0.001751033 0.001751016 0.001755231 0.001735053 0.001760936 0.001760005
##  [31] 0.001745170 0.001764558 0.001762836 0.001760769 0.001763160 0.001763365
##  [37] 0.001753472 0.001751740 0.001756954 0.001741945 0.001755206 0.001758761
##  [43] 0.001762607 0.001756507 0.001766694 0.001757460 0.001758264 0.001766278
##  [49] 0.001756863 0.001764872 0.001759314 0.001746725 0.001743440 0.001748409
##  [55] 0.001751804 0.001756929 0.001762636 0.001761945 0.001762079 0.001748849
##  [61] 0.001767126 0.001754744 0.001757028 0.001760267 0.001761626 0.001761003
##  [67] 0.001759223 0.001752654 0.001736453 0.001755908 0.001755228 0.001767379
##  [73] 0.001767367 0.001751495 0.001767196 0.001746317 0.001762616 0.001765885
##  [79] 0.001762521 0.001762927 0.001758108 0.001767462 0.001749393 0.001755565
##  [85] 0.001742422 0.001761904 0.001765699 0.001765102 0.001761522 0.001762779
##  [91] 0.001764932 0.001767439 0.001765151 0.001765455 0.001758257 0.001755893
##  [97] 0.001759139 0.001730483 0.001766910 0.001764128 0.001755708 0.001734346
## [103] 0.001742842 0.001759130 0.001739992 0.001767774 0.001756359 0.001737756
## [109] 0.001756464 0.001763508 0.001748224 0.001752883 0.001743155 0.001736292
## [115] 0.001758346 0.001761287 0.001766589 0.001736927 0.001762254 0.001744383
## [121] 0.001762685 0.001765790 0.001765361 0.001767540 0.001744260 0.001747350
## [127] 0.001752527 0.001761181 0.001759108 0.001763110 0.001760105 0.001766003
## [133] 0.001767055 0.001751448 0.001750302 0.001755796 0.001749806 0.001750948
## [139] 0.001767307 0.001765784 0.001762836 0.001757758 0.001754083 0.001761418
## [145] 0.001756079 0.001767387 0.001762203 0.001767274 0.001764549 0.001762386
## [151] 0.001749264 0.001760300 0.001751833 0.001736618 0.001762440 0.001759153
## [157] 0.001754285 0.001765336 0.001764367 0.001767013 0.001767383 0.001767269
## [163] 0.001754527 0.001748498 0.001750715 0.001742166 0.001755060 0.001761903
## [169] 0.001748356 0.001761727 0.001761164 0.001747286 0.001751102 0.001754087
## [175] 0.001744248 0.001757959 0.001757306 0.001761518 0.001766171 0.001757603
## [181] 0.001766809 0.001741812 0.001740060 0.001755240 0.001767150 0.001760545
## [187] 0.001748382 0.001757555 0.001761556 0.001761166 0.001748735 0.001756359
## [193] 0.001745720 0.001755192 0.001759528 0.001753404 0.001764040 0.001760419
## [199] 0.001756500 0.001748431 0.001761892 0.001748498 0.001757156 0.001761212
## [205] 0.001765542 0.001746690 0.001760208 0.001749652 0.001733395 0.001761308
## [211] 0.001739347 0.001758529 0.001766596 0.001751756 0.001760285 0.001742396
## [217] 0.001767100 0.001762099 0.001758412 0.001758304 0.001763696 0.001756866
## [223] 0.001762230 0.001767592 0.001749126 0.001760298 0.001751704 0.001756224
## [229] 0.001756417 0.001762796 0.001756567 0.001765829 0.001760731 0.001749195
## [235] 0.001760727 0.001757950 0.001761995 0.001742493 0.001759066 0.001729830
## [241] 0.001762747 0.001751932 0.001764759 0.001766814 0.001753015 0.001766839
## [247] 0.001752535 0.001746816 0.001739182 0.001766442 0.001765137 0.001764999
## [253] 0.001754347 0.001754723 0.001744203 0.001754483 0.001764905 0.001767513
## [259] 0.001764996 0.001744919 0.001766697 0.001762101 0.001750339 0.001760058
## [265] 0.001754813 0.001763249 0.001760082 0.001760226 0.001764667 0.001759450
## [271] 0.001761649 0.001751798 0.001764799 0.001763439 0.001747662 0.001760199
## [277] 0.001746801 0.001763182 0.001765078 0.001748030 0.001750350 0.001744768
## [283] 0.001759527 0.001743607 0.001753734 0.001757182 0.001763406 0.001763308
## [289] 0.001741465 0.001759708 0.001759062 0.001757920 0.001751219 0.001763865
## [295] 0.001761132 0.001751339 0.001755928 0.001755457 0.001761442 0.001765211
## [301] 0.001762024 0.001756012 0.001764594 0.001738206 0.001760064 0.001754200
## [307] 0.001750156 0.001750592 0.001767069 0.001754057 0.001740034 0.001765006
## [313] 0.001765256 0.001748152 0.001757933 0.001759650 0.001756010 0.001760037
## [319] 0.001761919 0.001766025 0.001767320 0.001762424 0.001759934 0.001744095
## [325] 0.001767700 0.001742508 0.001756902 0.001757718 0.001742278 0.001765579
## [331] 0.001764657 0.001749515 0.001737479 0.001724735 0.001738312 0.001760005
## [337] 0.001753564 0.001754181 0.001748852 0.001761966 0.001762699 0.001758011
## [343] 0.001750587 0.001757174 0.001752124 0.001751747 0.001748435 0.001750817
## [349] 0.001757775 0.001761132 0.001750110 0.001747679 0.001753697 0.001750897
## [355] 0.001751740 0.001759725 0.001749782 0.001753513 0.001757530 0.001763843
## [361] 0.001763733 0.001758514 0.001766172 0.001764890 0.001764574 0.001766860
## [367] 0.001752969 0.001765239 0.001763392 0.001762158 0.001749222 0.001748908
## [373] 0.001757864 0.001747679 0.001757795 0.001756453 0.001761272 0.001755639
## [379] 0.001757465 0.001746263 0.001735402 0.001762617 0.001754093 0.001765067
## [385] 0.001755695 0.001748914 0.001767267 0.001763191 0.001753635 0.001755563
## [391] 0.001765346 0.001715678 0.001762763 0.001765528 0.001763871 0.001756626
## [397] 0.001755152 0.001759361 0.001759938 0.001760095 0.001763815 0.001767212
## [403] 0.001741956 0.001764889 0.001762790 0.001752543 0.001751365 0.001767582
## [409] 0.001759217 0.001765487 0.001757319 0.001753430 0.001753813 0.001754799
## [415] 0.001766808 0.001755446 0.001759817 0.001764570 0.001742213 0.001749280
## [421] 0.001755342 0.001754608 0.001764150 0.001746624 0.001767708 0.001756507
## [427] 0.001743910 0.001752162 0.001745069 0.001762304 0.001752073 0.001755657
## [433] 0.001766226 0.001752116 0.001756542 0.001751316 0.001762555 0.001764735
## [439] 0.001744204 0.001759003 0.001749497 0.001763168 0.001751903 0.001767391
## [445] 0.001750663 0.001734139 0.001736882 0.001761316 0.001762479 0.001738449
## [451] 0.001766642 0.001759857 0.001744005 0.001755709 0.001747739 0.001760535
## [457] 0.001763684 0.001759548 0.001761965 0.001766807 0.001745744 0.001717467
## [463] 0.001756095 0.001756605 0.001767473 0.001761230 0.001766192 0.001746574
## [469] 0.001766311 0.001765751
proba_1=(length(m_t[m_t<1.767848e-03])/nsim)*100
proba_1
## [1] 47
#-----------------------------------
#ESTIMACION DEL PROCESO DE ITO POR EL METODO DE BLACK-SCHOLES
# Parámetros
S0 <-1.767848e-03   # Retorno inicial de la acción
mu <- mean(Retorno_portafolio_i)  # Tasa de retorno esperada
sigma <- sd(Retorno_portafolio_i)  # Volatilidad
n <- 1000  # Número de pasos
T <- 365     # Tiempo total (en años)
dt <- T/n  # Incremento de tiempo

# Simulación del proceso de Itô
set.seed(123)  # Para reproducibilidad
W <- cumsum(c(0, sqrt(dt) * rnorm(n)))
t <- seq(0, T, length.out = n+1)
S <- S0 * exp((mu - 0.5 * sigma^2) * t + sigma * W)

# Gráfico del proceso de Itô
plot(t, S, type = "l", main = "Proceso de Itô (Modelo de Black-Scholes) Portafolio 1", xlab = "Tiempo", ylab = "Retorno del Portafolio")

#---------------------------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------------------
# Parámetros
num_sim <- 1000  # Número de simulaciones
S0 <- 1.767848e-03 
mu <- mean(Retorno_portafolio_i)
sigma <- sd(Retorno_portafolio_i)
n <- 1000
T <- 365
dt <- T/n

# Función para simular una trayectoria del Retorno del Portafolio
simulate_stock_price <- function() {
  W <- cumsum(c(0, sqrt(dt) * rnorm(n)))
  t <- seq(0, T, length.out = n+1)
  S <- S0 * exp((mu - 0.5 * sigma^2) * t + sigma * W)
  return(S)
}

# Realizar múltiples simulaciones
set.seed(123)
simulations <- replicate(num_sim, simulate_stock_price())

# Gráfico de las simulaciones
matplot(seq(0, T, length.out = n+1), simulations, type = "l", lty = 1, col = rainbow(num_sim), main = "Simulaciones de los Retornos del Portafolio", xlab = "Tiempo", ylab = "Retornos")

##PORTAFOLIO DE PESOS IGUALES##———-

tail(Retorno_portafolio_iguales)
##            Retorno del Portafolio con Pesos Iguales
## 2024-05-22                            -1.439267e-03
## 2024-05-23                            -1.618227e-02
## 2024-05-24                             2.297786e-03
## 2024-05-28                            -4.235619e-03
## 2024-05-29                            -9.268001e-03
## 2024-05-30                             3.813593e-05
length(Retorno_portafolio_iguales)
## [1] 3625
sesgo <- skewness(Retorno_portafolio_iguales)
sesgo
## [1] -0.3923837
## attr(,"method")
## [1] "moment"
kurtosis(Retorno_portafolio_iguales)
## [1] 9.441127
## attr(,"method")
## [1] "excess"
#hist(Retorno_portafolio_i)
summary(Retorno_portafolio_iguales)
##      Index            Retorno del Portafolio con Pesos Iguales
##  Min.   :2010-01-05   Min.   :-0.0856766                      
##  1st Qu.:2013-08-12   1st Qu.:-0.0038652                      
##  Median :2017-03-17   Median : 0.0006949                      
##  Mean   :2017-03-17   Mean   : 0.0003777                      
##  3rd Qu.:2020-10-21   3rd Qu.: 0.0049117                      
##  Max.   :2024-05-30   Max.   : 0.0823394
#MOVIMIENTO GEOMETRICO ESTANDAR O PROCESO DE WEINER PARA EL PROTAFOLIO DE PESOS IGUALES
# Definir parámetros
set.seed(123)  # Para reproducibilidad
n <- 1000  # Número de pasos
T <- 365  # Tiempo total
dt <- T/n  # Incremento de tiempo

# Generar el proceso de Wiener
Wi <- c(0, cumsum(rnorm(n, mean = mean(Retorno_portafolio_iguales), sd = sd(Retorno_portafolio_iguales))))

# Crear un data frame para graficar
datai <- data.frame(Time = 0:n * dt, Wiener_Processi = Wi)
# Graficar el proceso de Wiener
ggplot(datai, aes(x = Time, y = Wiener_Processi)) +
  geom_line(color = "blue") +
  labs(title = "Simulación del Proceso de Wiener del portafolio 2",
       x = "Tiempo",
       y = "Valor del Proceso")

#SIMULACION DEL PROCEOS DE WEINER POR MBG PARA EL PORTAFOLIO DE PESOS IGUALES
t<-365
tseq<- 1:t
dt <- 1/t
muCi<-mean(Retorno_portafolio_iguales)
sCi<-sd(Retorno_portafolio_iguales)
P0i<- 3.813638e-05
xi <- P0i
nsim<- 1000
mi<- matrix(ncol = nsim, nrow = t)
for (i in 1:nsim) {
  mi[1,i] <- P0i
  for (h in 2:t) {
    e <- rnorm(1)
    mi[h, i]<- mi[(h-1),i]*exp((muCi-(sCi^2)/2)*dt+sCi*e*sqrt(dt))
  }
}

gbm_dfi <- as.data.frame(mi) %>%
  mutate(tiempo = 1:nrow(mi)) %>%
  pivot_longer(-tiempo, names_to = 'sim', values_to = 'Retorno')

gbm_dfi %>%
  ggplot(aes(x=tiempo, y=Retorno, color=sim)) +
  geom_line() +
  theme(legend.position = 'none')

#-------------------------------------------------------------------------
m2i<-t(mi)
plot(tseq, m2i[1, ],xlab = "Tiempo", ylab = "Retorno", type = "l",ylim = c(min(m2i[1, ])/1.1,max(m2i[1, ])*1.1))
apply(m2i[2:nsim, ],MARGIN =  1, function(xi, r){
  lines(tseq, xi)
})

## NULL
#GRAFICO DE LAS PROYECCIONES
proyeccion3=matrix(nrow =(3625+364),ncol = 1 )
proyeccion3[1:3625]=Retorno_portafolio_iguales
matplot(proyeccion3,type="l",ylim=c(-0.05,0.05))
proyeccion4=matrix(nrow = (3625+364),ncol = nsim)
proyeccion4[3625:3989,]=mi
matlines(proyeccion4,type = "l")

#intervalos de confianza
alfa=0.05
q1i=quantile(mi[t,],(alfa/2))
q2i=quantile(mi[t,],(1-alfa/2))
#------------------------------------
#Distribucion de los retornos futuros 
plot(density(mi[t,]),ylab="",xlab="",
     main="Empirical Distribution",lwd=3)
abline(h=NULL,v=q1i,col="blue",lwd=2)
abline(h=NULL,v=q2i,col="green",lwd=2)

#Probabilidad de que los retornos en 364 dias sean menores que el retorno inicial 
m_ti=mi[t,]
m_ti[m_ti<3.813638e-05]
##   [1] 3.766545e-05 3.808262e-05 3.795870e-05 3.804951e-05 3.774635e-05
##   [6] 3.765796e-05 3.808947e-05 3.801529e-05 3.797162e-05 3.798219e-05
##  [11] 3.770482e-05 3.772301e-05 3.789337e-05 3.810645e-05 3.775045e-05
##  [16] 3.760114e-05 3.784912e-05 3.757201e-05 3.804463e-05 3.781758e-05
##  [21] 3.763990e-05 3.792650e-05 3.803624e-05 3.797194e-05 3.776057e-05
##  [26] 3.776018e-05 3.785440e-05 3.740348e-05 3.798193e-05 3.796111e-05
##  [31] 3.762954e-05 3.806288e-05 3.802438e-05 3.797818e-05 3.803163e-05
##  [36] 3.803622e-05 3.781509e-05 3.777636e-05 3.789290e-05 3.755747e-05
##  [41] 3.785383e-05 3.793329e-05 3.801928e-05 3.788292e-05 3.811064e-05
##  [46] 3.790421e-05 3.792219e-05 3.810134e-05 3.789087e-05 3.806991e-05
##  [51] 3.794566e-05 3.766429e-05 3.759089e-05 3.770191e-05 3.777781e-05
##  [56] 3.789234e-05 3.801993e-05 3.800448e-05 3.800748e-05 3.771176e-05
##  [61] 3.812029e-05 3.784351e-05 3.789456e-05 3.796695e-05 3.799735e-05
##  [66] 3.798341e-05 3.794361e-05 3.779679e-05 3.743475e-05 3.786953e-05
##  [71] 3.785432e-05 3.812595e-05 3.812569e-05 3.777089e-05 3.812187e-05
##  [76] 3.765518e-05 3.801947e-05 3.809255e-05 3.801735e-05 3.802643e-05
##  [81] 3.791871e-05 3.812782e-05 3.772392e-05 3.786186e-05 3.756812e-05
##  [86] 3.800355e-05 3.808840e-05 3.807505e-05 3.799501e-05 3.802312e-05
##  [91] 3.807124e-05 3.812729e-05 3.807614e-05 3.808294e-05 3.792204e-05
##  [96] 3.786918e-05 3.794174e-05 3.730137e-05 3.811547e-05 3.805327e-05
## [101] 3.786504e-05 3.738768e-05 3.757751e-05 3.794155e-05 3.751384e-05
## [106] 3.813478e-05 3.787961e-05 3.746386e-05 3.788195e-05 3.803941e-05
## [111] 3.769778e-05 3.780192e-05 3.758450e-05 3.743115e-05 3.792402e-05
## [116] 3.798975e-05 3.810829e-05 3.744536e-05 3.801137e-05 3.761194e-05
## [121] 3.802101e-05 3.809043e-05 3.808085e-05 3.812956e-05 3.760921e-05
## [126] 3.767826e-05 3.779396e-05 3.798740e-05 3.794106e-05 3.803051e-05
## [131] 3.796335e-05 3.809519e-05 3.811871e-05 3.776984e-05 3.774422e-05
## [136] 3.786702e-05 3.773313e-05 3.775867e-05 3.812436e-05 3.809030e-05
## [141] 3.802439e-05 3.791088e-05 3.782873e-05 3.799269e-05 3.787335e-05
## [146] 3.812614e-05 3.801024e-05 3.812361e-05 3.806269e-05 3.801433e-05
## [151] 3.772103e-05 3.796771e-05 3.777844e-05 3.743845e-05 3.801553e-05
## [156] 3.794207e-05 3.783325e-05 3.808029e-05 3.805862e-05 3.811778e-05
## [161] 3.812605e-05 3.812350e-05 3.783865e-05 3.770391e-05 3.775346e-05
## [166] 3.756240e-05 3.785058e-05 3.800353e-05 3.770073e-05 3.799960e-05
## [171] 3.798702e-05 3.767683e-05 3.776211e-05 3.782882e-05 3.760893e-05
## [176] 3.791537e-05 3.790078e-05 3.799494e-05 3.809896e-05 3.790741e-05
## [181] 3.811322e-05 3.755450e-05 3.751535e-05 3.785460e-05 3.812083e-05
## [186] 3.797319e-05 3.770132e-05 3.790635e-05 3.799577e-05 3.798706e-05
## [191] 3.770920e-05 3.787961e-05 3.764184e-05 3.785352e-05 3.795044e-05
## [196] 3.781355e-05 3.805131e-05 3.797037e-05 3.788276e-05 3.770242e-05
## [201] 3.800328e-05 3.770390e-05 3.789742e-05 3.798809e-05 3.808488e-05
## [206] 3.766350e-05 3.796565e-05 3.772969e-05 3.736644e-05 3.799023e-05
## [211] 3.749941e-05 3.792810e-05 3.810845e-05 3.777672e-05 3.796736e-05
## [216] 3.756756e-05 3.811972e-05 3.800791e-05 3.792549e-05 3.792308e-05
## [221] 3.804362e-05 3.789095e-05 3.801085e-05 3.813073e-05 3.771794e-05
## [226] 3.796765e-05 3.777556e-05 3.787659e-05 3.788090e-05 3.802350e-05
## [231] 3.788427e-05 3.809131e-05 3.797732e-05 3.771949e-05 3.797726e-05
## [236] 3.791517e-05 3.800558e-05 3.756971e-05 3.794011e-05 3.728680e-05
## [241] 3.802239e-05 3.778065e-05 3.806739e-05 3.811332e-05 3.780486e-05
## [246] 3.811389e-05 3.779413e-05 3.766633e-05 3.749574e-05 3.810501e-05
## [251] 3.807584e-05 3.807274e-05 3.783463e-05 3.784304e-05 3.760793e-05
## [256] 3.783767e-05 3.807064e-05 3.812895e-05 3.807267e-05 3.762394e-05
## [261] 3.811071e-05 3.800797e-05 3.774506e-05 3.796230e-05 3.784505e-05
## [266] 3.803363e-05 3.796283e-05 3.796604e-05 3.806532e-05 3.794871e-05
## [271] 3.799786e-05 3.777766e-05 3.806828e-05 3.803787e-05 3.768522e-05
## [276] 3.796543e-05 3.766600e-05 3.803212e-05 3.807452e-05 3.769344e-05
## [281] 3.774531e-05 3.762056e-05 3.795041e-05 3.759461e-05 3.782093e-05
## [286] 3.789801e-05 3.803713e-05 3.803494e-05 3.754674e-05 3.795446e-05
## [291] 3.794002e-05 3.791451e-05 3.776473e-05 3.804739e-05 3.798630e-05
## [296] 3.776741e-05 3.786997e-05 3.785944e-05 3.799323e-05 3.807748e-05
## [301] 3.800624e-05 3.787185e-05 3.806368e-05 3.747391e-05 3.796242e-05
## [306] 3.783136e-05 3.774097e-05 3.775071e-05 3.811903e-05 3.782815e-05
## [311] 3.751478e-05 3.807290e-05 3.807849e-05 3.769619e-05 3.791479e-05
## [316] 3.795318e-05 3.787181e-05 3.796183e-05 3.800388e-05 3.809567e-05
## [321] 3.812463e-05 3.801517e-05 3.795951e-05 3.760552e-05 3.813313e-05
## [326] 3.757006e-05 3.789175e-05 3.790997e-05 3.756490e-05 3.808572e-05
## [331] 3.806510e-05 3.772665e-05 3.745769e-05 3.717298e-05 3.747629e-05
## [336] 3.796111e-05 3.781713e-05 3.783092e-05 3.771182e-05 3.800495e-05
## [341] 3.802133e-05 3.791653e-05 3.775061e-05 3.789783e-05 3.778494e-05
## [346] 3.777652e-05 3.770250e-05 3.775574e-05 3.791126e-05 3.798630e-05
## [351] 3.773994e-05 3.768560e-05 3.782010e-05 3.775752e-05 3.777637e-05
## [356] 3.795484e-05 3.773261e-05 3.781598e-05 3.790578e-05 3.804689e-05
## [361] 3.804443e-05 3.792779e-05 3.809897e-05 3.807030e-05 3.806324e-05
## [366] 3.811436e-05 3.780383e-05 3.807812e-05 3.803683e-05 3.800923e-05
## [371] 3.772008e-05 3.771308e-05 3.791324e-05 3.768562e-05 3.791171e-05
## [376] 3.788171e-05 3.798943e-05 3.786350e-05 3.790433e-05 3.765396e-05
## [381] 3.741128e-05 3.801951e-05 3.782896e-05 3.807427e-05 3.786477e-05
## [386] 3.771321e-05 3.812346e-05 3.803232e-05 3.781872e-05 3.786181e-05
## [391] 3.808051e-05 3.697069e-05 3.802276e-05 3.808458e-05 3.804752e-05
## [396] 3.788557e-05 3.785264e-05 3.794671e-05 3.795962e-05 3.796312e-05
## [401] 3.804628e-05 3.812223e-05 3.755772e-05 3.807028e-05 3.802337e-05
## [406] 3.779432e-05 3.776800e-05 3.813050e-05 3.794350e-05 3.808365e-05
## [411] 3.790107e-05 3.781415e-05 3.782270e-05 3.784473e-05 3.811319e-05
## [416] 3.785919e-05 3.795691e-05 3.806317e-05 3.756347e-05 3.772138e-05
## [421] 3.785687e-05 3.784048e-05 3.805377e-05 3.766204e-05 3.813331e-05
## [426] 3.788291e-05 3.760138e-05 3.778581e-05 3.762728e-05 3.801251e-05
## [431] 3.778380e-05 3.786391e-05 3.810018e-05 3.778477e-05 3.788370e-05
## [436] 3.776689e-05 3.801810e-05 3.806684e-05 3.760795e-05 3.793872e-05
## [441] 3.772624e-05 3.803181e-05 3.778002e-05 3.812622e-05 3.775231e-05
## [446] 3.738305e-05 3.744434e-05 3.799041e-05 3.801641e-05 3.747936e-05
## [451] 3.810947e-05 3.795780e-05 3.760351e-05 3.786507e-05 3.768695e-05
## [456] 3.797294e-05 3.804334e-05 3.795089e-05 3.800493e-05 3.811316e-05
## [461] 3.764235e-05 3.701063e-05 3.787372e-05 3.788510e-05 3.812807e-05
## [466] 3.798849e-05 3.809942e-05 3.766092e-05 3.810207e-05 3.808956e-05
proba=(length(m_ti[m_ti<3.813638e-05])/nsim)*100
proba
## [1] 47
#-----------------------------------
#ESTIMACION DEL PROCESO DE ITO POR EL METODO DE BLACK-SCHOLES
# Parámetros
S0 <-3.813638e-05   # Retorno inicial de la acción
mui <- mean(Retorno_portafolio_iguales)  # Tasa de retorno esperada
sigmai <- sd(Retorno_portafolio_iguales)  # Volatilidad
n <- 1000  # Número de pasos
T <- 365     # Tiempo total (en años)
dt <- T/n  # Incremento de tiempo

# Simulación del proceso de Itô
set.seed(123)  # Para reproducibilidad
W <- cumsum(c(0, sqrt(dt) * rnorm(n)))
t <- seq(0, T, length.out = n+1)
S <- S0 * exp((mui - 0.5 * sigmai^2) * t + sigmai * W)

# Gráfico del proceso de Itô
plot(t, S, type = "l", main = "Proceso de Itô (Modelo de Black-Scholes): Portafolio 2", xlab = "Tiempo", ylab = "Retorno del Portafolio")

#---------------------------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------------------
# Parámetros
num_sim <- 1000  # Número de simulaciones
S0 <- 3.813638e-05 
mui <- mean(Retorno_portafolio_iguales)
sigmai <- sd(Retorno_portafolio_iguales)
n <- 1000
T <- 365
dt <- T/n

# Función para simular una trayectoria del Retorno del Portafolio
simulate_stock_price <- function() {
  W <- cumsum(c(0, sqrt(dt) * rnorm(n)))
  t <- seq(0, T, length.out = n+1)
  S <- S0 * exp((mui - 0.5 * sigmai^2) * t + sigmai * W)
  return(S)
}

# Realizar múltiples simulaciones
set.seed(123)
simulations <- replicate(num_sim, simulate_stock_price())

# Gráfico de las simulaciones
matplot(seq(0, T, length.out = n+1), simulations, type = "l", lty = 1, col = rainbow(num_sim), main = "Simulaciones de los Retornos del Portafolio de Pesos Iguales", xlab = "Tiempo", ylab = "Retornos")