#Importar los datos El activo es AAPL (Apple)

l_data <- getSymbols("AAPL", from = "2021-03-16", to = "2024-03-16", auto.assign = FALSE) TBill_data <- getSymbols("TLT", from = "2021-03-16", to = "2024-03-16", auto.assign = FALSE)

Retornos
ret_aapl <- Delt(aapl_data$AAPL.Adjusted)
ret_tbill <- Delt(TBill_data$TLT.Adjusted)

rets <- cbind(ret_aapl, ret_tbill)
names(rets) <- c("AAPL", "TBILL")
head(rets)

#####Retornos acumulados

rets[1, ] <- c(0, 0)
gross_ret <- 1 + rets

cum_rets <- cumprod(gross_ret)
head(cum_rets)

plot(cum_rets$AAPL, 
     main = "Value of 1 USD invested")
lines(cum_rets$TBILL, col = "blue", lwd = 3)

tail(cum_rets, 2)
tail((cum_rets - 1) * 100, 2)
head(cum_rets)
Grafica de retornos
plot(rets$AAPL, col = "red", 
     main = "Retornos AAPL y T-Bills")
lines(rets$TBILL, col = "pink", lwd = 5)
plot(rets$TBILL, col = "pink", 
     main = "Retornos TBILL")

#####Calculo de la desviación estandar

head(rets)
returns <- rets[-1, ]

sd_aapl <- sd(returns$AAPL)
sd_aapl

sd_tbill <- sd(returns$TBILL)
sd_tbill
Riesgo cambio en el tiempo
typeof(index(returns))
str(index(returns))
Desviación cada año- Total
sd_2021 <- apply(returns["2021"], 2, sd)
sd_2021

sd_2022 <- apply(returns["2022"], 2, sd)
sd_2022

sd_2023 <- apply(returns["2023"], 2, sd)
sd_2023

sd_2024 <- apply(returns["2024"], 2, sd)
sd_2024
Datos de desviación diarios
sd_todo <- rbind(sd_2021, sd_2022, sd_2023, sd_2024)
head(sd_todo)

sd_anual <- sqrt(252) * sd_todo
sd_anual
Grafico de desviación estandar anualizada
barplot(t(sd_anual), beside = TRUE, 
        col = c("blue", "red"),
        main = "Desv. Estandar anualizada AAPL Y T-Bill", 
        legend.text = c("AAPL", "T-Bill"))
Histogramas
hist(returns$AAPL, breaks = 50)
hist(returns$TBILL, breaks = 5)