# Cargar librerías necesarias
library(quantmod)
## Warning: package 'quantmod' was built under R version 4.4.3
## 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
## Warning: package 'TTR' was built under R version 4.4.3
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(splines)
library(ggplot2)
library(nnet)

# Obtener precios históricos de Apple
getSymbols("AAPL", from = "2018-01-01", to = "2023-12-31")
## [1] "AAPL"
precios <- Cl(AAPL)
datos <- data.frame(
  t = 1:length(precios),
  precio = as.numeric(precios)
)

# LOWESS
ggplot(datos, aes(x = t, y = precio)) +
  geom_point(alpha = 0.2, color = "gray") +
  geom_smooth(method = "loess", se = FALSE, color = "blue") +
  labs(title = "LOWESS - Precio AAPL", x = "Tiempo", y = "Precio") +
  theme_minimal()
## `geom_smooth()` using formula = 'y ~ x'

ggsave("apple_lowess.png", width = 8, height = 5)
## `geom_smooth()` using formula = 'y ~ x'
# K-spline
modelo_spline <- lm(precio ~ bs(t, df = 15), data = datos)
datos$pred_spline <- predict(modelo_spline)

ggplot(datos, aes(x = t)) +
  geom_point(aes(y = precio), alpha = 0.2, color = "gray") +
  geom_line(aes(y = pred_spline), color = "darkgreen") +
  labs(title = "K-Spline - Precio AAPL", x = "Tiempo", y = "Precio") +
  theme_minimal()

ggsave("apple_spline.png", width = 8, height = 5)

# Red neuronal (una capa oculta)
set.seed(123)
modelo_nn <- nnet(precio ~ t, data = datos, size = 10, linout = TRUE, maxit = 500)
## # weights:  31
## initial  value 21763041.477636 
## iter  10 value 3411350.738472
## iter  20 value 400714.751536
## iter  30 value 237374.216683
## iter  40 value 223140.038858
## iter  50 value 172523.031338
## iter  60 value 152863.373646
## iter  70 value 126638.877702
## iter  80 value 119971.556127
## iter  90 value 118846.942121
## iter 100 value 118561.196437
## iter 110 value 111524.024750
## iter 120 value 106107.964382
## iter 130 value 104268.539994
## iter 140 value 101926.888129
## iter 150 value 99671.745598
## iter 160 value 96459.335174
## iter 170 value 92667.675924
## iter 180 value 85719.399986
## iter 190 value 85369.593742
## iter 200 value 80548.228458
## iter 210 value 79739.876632
## iter 220 value 79555.910154
## iter 230 value 79523.341178
## iter 240 value 79487.184454
## iter 250 value 79466.628343
## iter 260 value 79441.945132
## iter 270 value 79360.025216
## iter 280 value 79038.852138
## iter 290 value 77785.453601
## iter 300 value 75021.322424
## iter 310 value 73707.446008
## iter 320 value 72875.103767
## iter 330 value 71899.237931
## final  value 71884.325153 
## converged
datos$pred_nn <- predict(modelo_nn)

ggplot(datos, aes(x = t)) +
  geom_point(aes(y = precio), alpha = 0.2, color = "gray") +
  geom_line(aes(y = pred_nn), color = "red") +
  labs(title = "Red Neuronal - Precio AAPL", x = "Tiempo", y = "Precio") +
  theme_minimal()

ggsave("apple_nn.png", width = 8, height = 5)


# Calcular errores
errores <- data.frame(
  modelo = c("LOWESS", "K-Spline", "Red Neuronal"),
  SCE = c(
    sum((datos$precio - predict(loess(precio ~ t, data = datos)))^2),
    sum((datos$precio - datos$pred_spline)^2),
    sum((datos$precio - datos$pred_nn)^2)
  ),
  CME = c(
    mean((datos$precio - predict(loess(precio ~ t, data = datos)))^2),
    mean((datos$precio - datos$pred_spline)^2),
    mean((datos$precio - datos$pred_nn)^2)
  ),
  MAE = c(
    mean(abs(datos$precio - predict(loess(precio ~ t, data = datos)))),
    mean(abs(datos$precio - datos$pred_spline)),
    mean(abs(datos$precio - datos$pred_nn))
  ),
  MdAE = c(
    median(abs(datos$precio - predict(loess(precio ~ t, data = datos)))),
    median(abs(datos$precio - datos$pred_spline)),
    median(abs(datos$precio - datos$pred_nn))
  )
)

# Redondear solo columnas numéricas (sin afectar 'modelo')
errores_redondeados <- errores
errores_redondeados[,-1] <- round(errores_redondeados[,-1], 3)

# Mostrar
print(errores_redondeados)
##         modelo       SCE     CME   MAE  MdAE
## 1       LOWESS 184186.75 122.059 8.461 6.393
## 2     K-Spline  71156.58  47.155 5.237 4.325
## 3 Red Neuronal  71884.32  47.637 5.385 4.413