# =========================================================
# 1. LIBRERÍAS
# =========================================================
library(derivmkts)
library(quantmod)
library(plotly)
library(knitr)

# =========================================================
# 2. DATOS DEL ACTIVO (JNJ)
# =========================================================
getSymbols("JNJ", src = "yahoo", auto.assign = TRUE)
## [1] "JNJ"
S_val <- as.numeric(last(Cl(JNJ)))
K_val <- round(S_val, 0) 

# =========================================================
# 3. PARÁMETROS FINANCIEROS
# =========================================================
r_tasa <- 0.045     # Tasa SOFR aproximada
q_div  <- 0.028     # Dividend Yield JNJ
tiempos_v <- seq(1, 1/12, length.out = 12) 
sigmas_v  <- seq(0.16, 0.18, length.out = 12) 

# =========================================================
# 4. RANGO DE PRECIOS PARA SIMULACIÓN (EJE X)
# =========================================================
set.seed(123)
ST_sim <- S_val * exp((r_tasa - q_div - 0.5 * 0.18^2) * 1 + 0.18 * sqrt(1) * rnorm(5000))
S_grid <- seq(round(quantile(ST_sim, 0.025), 0), 
              round(quantile(ST_sim, 0.975), 0), by = 2)

# =========================================================
# 5. FUNCIÓN DE CÁLCULO (MOTOR DE GRIEGAS)
# =========================================================
calcular_todo <- function(idx) {
  TT <- tiempos_v[idx]
  VV <- sigmas_v[idx]
  precios <- bscall(S_grid, K_val, VV, r_tasa, TT, q_div)
  
  d1 <- (log(S_grid / K_val) + (r_tasa - q_div + 0.5 * VV^2) * TT) / (VV * sqrt(TT))
  d2 <- d1 - VV * sqrt(TT)
  
  deltas <- exp(-q_div * TT) * pnorm(d1)
  gammas <- (exp(-q_div * TT) * dnorm(d1)) / (S_grid * VV * sqrt(TT))
  vegas  <- (S_grid * exp(-q_div * TT) * dnorm(d1) * sqrt(TT)) / 100
  rhos   <- (K_val * TT * exp(-r_tasa * TT) * pnorm(d2)) / 100
  
  # Theta Diario
  t1 <- -(S_grid * VV * exp(-q_div * TT) * dnorm(d1)) / (2 * sqrt(TT))
  t2 <- -r_tasa * K_val * exp(-r_tasa * TT) * pnorm(d2)
  t3 <- q_div * S_grid * exp(-q_div * TT) * pnorm(d1)
  thetas <- (t1 + t2 + t3) / 365
  
  return(list(p = precios, d = deltas, g = gammas, v = vegas, th = thetas, r = rhos))
}

m12 <- calcular_todo(12) # Datos al inicio (1 año)
m1  <- calcular_todo(1)  # Datos al vencimiento (1 mes)

# =========================================================
# 6. GENERACIÓN DE GRÁFICAS (FORMATO PUNTOS Y LÍNEAS)
# =========================================================

# FIGURA 1: CONVEXIDAD (Precio de la opción)
f1 <- plot_ly(x = S_grid) %>%
  add_lines(y = m12$p, name = "Inicio (M12)") %>%
  add_lines(y = m1$p,  name = "Final (M1)", line = list(width = 4)) %>%
  layout(title = "Convexidad de la Opción Call JNJ", 
         xaxis = list(title = "Precio Acción"), yaxis = list(title = "Valor Opción"))

# FIGURA 2: DELTA
f2 <- plot_ly(x = S_grid) %>%
  add_trace(y = m12$d, name = "D12", type = 'scatter', mode = 'lines+markers', marker = list(color = 'darkgreen')) %>%
  add_trace(y = m1$d,  name = "D1",  type = 'scatter', mode = 'lines+markers', marker = list(color = 'lightgreen')) %>%
  layout(title = "Análisis de Delta (Sensibilidad al Precio)", 
         xaxis = list(title = "Precio Acción"), yaxis = list(title = "Delta"))

# FIGURA 3: GAMMA
f3 <- plot_ly(x = S_grid) %>%
  add_trace(y = m12$g, name = "G12", type = 'scatter', mode = 'lines+markers') %>%
  add_trace(y = m1$g,  name = "G1",  type = 'scatter', mode = 'lines+markers') %>%
  layout(title = "Análisis de Gamma (Riesgo de Curvatura)", 
         xaxis = list(title = "Precio Acción"), yaxis = list(title = "Gamma"))

# FIGURA 4: THETA
f4 <- plot_ly(x = S_grid) %>%
  add_trace(y = m12$th, name = "T12", type = 'scatter', mode = 'lines+markers') %>%
  add_trace(y = m1$th,  name = "T1",  type = 'scatter', mode = 'lines+markers') %>%
  layout(title = "Análisis de Theta (Decaimiento Temporal)", 
         xaxis = list(title = "Precio Acción"), yaxis = list(title = "Theta Diario"))

# FIGURA 5: VEGA
f5 <- plot_ly(x = S_grid) %>%
  add_trace(y = m12$v, name = "V12", type = 'scatter', mode = 'lines+markers') %>%
  add_trace(y = m1$v,  name = "V1",  type = 'scatter', mode = 'lines+markers') %>%
  layout(title = "Análisis de Vega (Impacto Volatilidad)", 
         xaxis = list(title = "Precio Acción"), yaxis = list(title = "Vega"))

# FIGURA 6: RHO
f6 <- plot_ly(x = S_grid) %>%
  add_trace(y = m12$r, name = "R12", type = 'scatter', mode = 'lines+markers') %>%
  add_trace(y = m1$r,  name = "R1",  type = 'scatter', mode = 'lines+markers') %>%
  layout(title = "Análisis de Rho (Impacto Tasa de Interés)", 
         xaxis = list(title = "Precio Acción"), yaxis = list(title = "Rho"))

# MOSTRAR GRÁFICAS
f1
f2
f3
f4
f5
f6
# =========================================================
# 7. TABLA DE DATOS PARA EL ANÁLISIS TÉCNICO
# =========================================================
idx_atm <- which.min(abs(S_grid - K_val))

tabla_analisis <- data.frame(
  Indicador = c("Precio Call", "Delta", "Gamma", "Theta Diario", "Vega", "Rho"),
  Valor_Inicio = c(m12$p[idx_atm], m12$d[idx_atm], m12$g[idx_atm], m12$th[idx_atm], m12$v[idx_atm], m12$r[idx_atm]),
  Valor_Final  = c(m1$p[idx_atm],  m1$d[idx_atm],  m1$g[idx_atm],  m1$th[idx_atm],  m1$v[idx_atm],  m1$r[idx_atm])
)

kable(tabla_analisis, digits = 4, caption = "Valores At-the-Money (Inicio vs Final)")
Valores At-the-Money (Inicio vs Final)
Indicador Valor_Inicio Valor_Final
Precio Call 4.5202 15.9020
Delta 0.4874 0.5478
Gamma 0.0327 0.0102
Theta Diario -0.0843 -0.0237
Vega 0.2687 0.8963
Rho 0.0913 1.1229