========== INSTALAR Y CARGAR LIBRERÍAS ==========

install.packages(c(“qrmtools”, “tidyquant”, “dplyr”, “MASS”, “timetk”, “PerformanceAnalytics”, “tidyverse”)) library(tidyquant) library(timetk) library(tidyverse) library(MASS) library(qrmtools) library(PerformanceAnalytics)

========== 1. DESCARGAR PRECIOS ==========

tickers <- c(“NVDA”, “F”, “PLTR”) benchmark <- “^GSPC” all_tickers <- c(tickers, benchmark) price_data <- tq_get(all_tickers, from = “2022-06-01”, to = Sys.Date(), get = “stock.prices”)

========== 2. CALCULAR RENDIMIENTOS LOGARÍTMICOS ==========

log_returns <- price_data %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = “daily”, col_rename = “ret”, type = “log”)

benchmark_returns <- log_returns %>% filter(symbol == benchmark) asset_returns <- log_returns %>% filter(symbol %in% tickers)

log_returns_xts <- asset_returns %>% spread(symbol, value = ret) %>% tk_xts()

========== 3. SIMULACIÓN MONTE CARLO ==========

num_simulations <- 10000 num_days <- 252 * 2 initial_investment <- 1e6 weights <- rep(1 / length(tickers), length(tickers))

mu <- colMeans(log_returns_xts, na.rm = TRUE) sigma <- cov(log_returns_xts, use = “complete.obs”)

simulated_prices <- matrix(NA, nrow = num_days, ncol = num_simulations)

for (i in 1:num_simulations) { simulated_returns <- mvrnorm(n = num_days, mu = mu, Sigma = sigma) portfolio_returns <- simulated_returns %% weights simulated_prices[, i] <- initial_investment exp(cumsum(portfolio_returns)) }

simulated_prices_df <- as.data.frame(simulated_prices)

========== 4. MÉTRICAS DEL PORTAFOLIO ==========

simulated_daily_returns <- apply(simulated_prices_df, 2, function(x) diff(log(x)))

portfolio_annual_returns <- colMeans(simulated_daily_returns) * 252 portfolio_annual_volatility <- apply(simulated_daily_returns, 2, sd) * sqrt(252) portfolio_sharpe <- portfolio_annual_returns / portfolio_annual_volatility

VaR_1 <- apply(simulated_daily_returns, 2, function(x) quantile(x, 0.01)) VaR_5 <- apply(simulated_daily_returns, 2, function(x) quantile(x, 0.05))

VaR_1_loss <- initial_investment * abs(mean(VaR_1)) VaR_5_loss <- initial_investment * abs(mean(VaR_5))

portfolio_summary <- tibble( Activo = “Portafolio (NVDA, F, PLTR)”, Retorno_Anualizado = mean(portfolio_annual_returns), Volatilidad_Anualizada = mean(portfolio_annual_volatility), Sharpe_Ratio = mean(portfolio_sharpe), VaR_1_percent = VaR_1_loss, VaR_5_percent = VaR_5_loss )

========== 5. MÉTRICAS DEL BENCHMARK ==========

benchmark_xts <- xts(benchmark_returns\(ret, order.by = benchmark_returns\)date) benchmark_return <- Return.annualized(benchmark_xts) benchmark_volatility <- StdDev.annualized(benchmark_xts) benchmark_sharpe <- SharpeRatio.annualized(benchmark_xts, Rf = 0) benchmark_VaR_1 <- VaR(benchmark_xts, p = 0.01, method = “historical”) benchmark_VaR_5 <- VaR(benchmark_xts, p = 0.05, method = “historical”)

benchmark_summary <- tibble( Activo = “S&P 500”, Retorno_Anualizado = as.numeric(benchmark_return), Volatilidad_Anualizada = as.numeric(benchmark_volatility), Sharpe_Ratio = as.numeric(benchmark_sharpe), VaR_1_percent = as.numeric(initial_investment * abs(benchmark_VaR_1)), VaR_5_percent = as.numeric(initial_investment * abs(benchmark_VaR_5)) )

========== 6. VALUACIÓN DE OPCIONES AMERICANAS ==========

american_option_binomial <- function(S, K, r, T, sigma, type = “call”, steps = 100) { dt <- T / steps u <- exp(sigma * sqrt(dt)) d <- 1 / u p <- (exp(r * dt) - d) / (u - d)

prices <- numeric(steps + 1) values <- numeric(steps + 1)

for (i in 0:steps) { prices[i + 1] <- S * u^i * d^(steps - i) values[i + 1] <- ifelse(type == “call”, max(0, prices[i + 1] - K), max(0, K - prices[i + 1])) }

for (j in (steps - 1):0) { for (i in 0:j) { prices[i + 1] <- S * u^i * d^(j - i) expected <- exp(-r * dt) * (p * values[i + 2] + (1 - p) * values[i + 1]) intrinsic <- ifelse(type == “call”, max(0, prices[i + 1] - K), max(0, K - prices[i + 1])) values[i + 1] <- max(expected, intrinsic) } } return(values[1]) }

S <- c(101.49, 9.63, 93.78) K <- S * 1.1 T <- 0.25 sigma <- c(0.3, 0.4, 0.35) r <- 0.048 K am_call_prices <- mapply(american_option_binomial, S, K, r, T, sigma, MoreArgs = list(type = “call”)) am_put_prices <- mapply(american_option_binomial, S, K, r, T, sigma, MoreArgs = list(type = “put”))

========== 7. COBERTURA CON OPCIONES AMERICANAS ==========

coverage_funds <- 0.85 * initial_investment weights_vol <- sigma / sum(sigma) allocated_funds <- weights_vol * coverage_funds contracts_allocated <- allocated_funds / ((am_call_prices + am_put_prices) * 100)

coverage_summary_am <- tibble( Acción = tickers, Precio_Acción = S, Precio_Contrato_Call = round(am_call_prices, 2), Precio_Contrato_Put = round(am_put_prices, 2), Fondos_Asignados = round(allocated_funds, 2), Contratos_Call = round(contracts_allocated, 0) )

========== 8. TABLA COMPARATIVA ==========

comparative_summary <- bind_rows(portfolio_summary, benchmark_summary) # ========== 9. VALUACIÓN DE OPCIONES EUROPEAS ========== black_scholes <- function(S, K, r, T, sigma, type = “call”) { d1 <- (log(S / K) + (r + 0.5 * sigma^2) * T) / (sigma * sqrt(T)) d2 <- d1 - sigma * sqrt(T) if (type == “call”) { return(S * pnorm(d1) - K * exp(-r * T) * pnorm(d2)) } else { return(K * exp(-r * T) * pnorm(-d2) - S * pnorm(-d1)) } }

Datos del mercado para valuación

S <- c(101.49, 9.63, 93.78) # Precios actuales K <- S * 1.1 # Precio strike al 110% T <- 0.25 # 3 meses hasta vencimiento sigma <- c(0.3, 0.4, 0.35) # Volatilidades r <- 0.048 # Tasa bono del tesoro 4.8%

Valuación de opciones europeas

euro_call_prices <- mapply(black_scholes, S, K, r, T, sigma, MoreArgs = list(type = “call”)) euro_put_prices <- mapply(black_scholes, S, K, r, T, sigma, MoreArgs = list(type = “put”))

========== 7. COBERTURA CON OPCIONES EUROPEAS ==========

coverage_funds_euro <- 0.85 * initial_investment

Asignación proporcional por volatilidad

weights_vol_euro <- sigma / sum(sigma) allocated_funds_euro <- weights_vol_euro * coverage_funds_euro

Cálculo de contratos necesarios

contracts_euro <- allocated_funds_euro / ((euro_call_prices + euro_put_prices) * 100)

Tabla resumen

coverage_summary_euro <- tibble( Acción = tickers, Precio_Acción = S, Precio_Contrato_Call = round(euro_call_prices, 2), Precio_Contrato_Put = round(euro_put_prices, 2), Fondos_Asignados = round(allocated_funds_euro, 2), Contratos_Necesarios = round(contracts_euro, 0) )

========== RESULTADOS ACTUALIZADOS ==========

print(coverage_summary_euro)

cat(“📌 COBERTURA CON OPCIONES EUROPEAS:”) cat(“Cobertura del 85% del capital apalancado.”) cat(“Asignación proporcional al riesgo (volatilidad de cada activo).”) cat(“Cada opción cubre 100 acciones.”) cat(“Las primas se pagan de forma trimestral.”) cat(“Estrategia válida: protección con puts, upside con calls (Protective Collar europea).”)

========== RESULTADOS ==========

print(coverage_summary_am) print(comparative_summary)

cat(“🔍 RESUMEN FINAL:”) cat(“El portafolio tiene mayor retorno anualizado que el benchmark,”) cat(“pero también una volatilidad más alta.”) cat(“El Sharpe ratio sugiere que el riesgo no está completamente compensado por el retorno.”) cat(“VaR al 1% implica una pérdida esperada máxima de: $”, format(round(VaR_1_loss, 2), big.mark = “,”), “”) cat(“VaR al 5% implica una pérdida esperada máxima de: $”, format(round(VaR_5_loss, 2), big.mark = “,”), “”) cat(“La cobertura con opciones americanas protege el 85% del capital apalancado usando un reparto proporcional al riesgo (volatilidad).”)

#ANALISIS OPCIONES AMERICANAS #El inversor solo aporta el 15% del capital propio. El 85% restante se financia con deuda, probablemente a una tasa como la del bono del Tesoro (4.8%). #Se busca proteger esa parte apalancada con opciones para limitar pérdidas en caso de caída del mercado #Los activos con más riesgo (volatilidad) necesitan mayor cobertura. Esta asignación es una estrategia válida y común: #NVDA y PLTR, más volátiles, reciben más contratos. #Ford (F), con menor volatilidad, necesita menos cobertura. #Cada opción se considera para un trimestre. Si se mantienen coberturas continuas: #Se renuevan contratos cada 3 meses. #Se pagan primas trimestralmente. #Se puede usar parte del rendimiento generado por el portafolio para cubrir futuras primas.

#Estrategia de cobertura (Protective Collar): #Call Americanas protegen contra movimientos alcistas y permiten aprovechar la apreciación. #Put Americanas te permiten ejercer antes del vencimiento si el precio cae mucho → esto limita pérdidas. #Se paga un premium, pero se obtiene una protección activa, ideal para activos volátiles como NVDA y PLTR.

#Justificación de reparto: #Se reparte proporcionalmente al riesgo (volatilidad) o a la exposición monetaria por acción.