renderPlot({
# Captura os valores dos inputs
mu1 <- input$mu1
mu2 <- input$mu2
rf <- input$rf
sigma1 <- input$sigma1
sigma2 <- input$sigma2
rho <- input$rho
incluir_rf <- input$incluir_rf
if (!incluir_rf) {
# Caso: apenas ativos de risco
w1 <- seq(0, 1, length.out = 200)
w2 <- 1 - w1
retorno_port <- w1 * mu1 + w2 * mu2
desvio_port <- sqrt( w1^2 * sigma1^2 +
w2^2 * sigma2^2 +
2 * w1 * w2 * rho * sigma1 * sigma2 )
df <- data.frame(Desvio = desvio_port, Retorno = retorno_port)
ggplot(df, aes(x = Desvio, y = Retorno)) +
geom_line(color = "blue", size = 1) +
labs(title = "Fronteira Eficiente - Apenas Ações",
x = "Desvio Padrão do Portfólio",
y = "Retorno Esperado do Portfólio") +
theme_minimal()
} else {
# Caso: incluindo a taxa livre de risco
Sigma <- matrix(c(sigma1^2, rho * sigma1 * sigma2,
rho * sigma1 * sigma2, sigma2^2), nrow = 2)
mu_risky <- c(mu1, mu2)
A <- mu_risky - rf
invSigma <- solve(Sigma)
w_t <- invSigma %*% A
w_t <- as.numeric(w_t / sum(w_t))
mu_t <- sum(w_t * mu_risky)
sigma_t <- sqrt( t(w_t) %*% Sigma %*% w_t )
lambda <- seq(0, 2, length.out = 200) # permitindo alavancagem
desvio_port <- lambda * sigma_t
retorno_port <- rf + lambda * (mu_t - rf)
df <- data.frame(Desvio = desvio_port, Retorno = retorno_port)
ggplot(df, aes(x = Desvio, y = Retorno)) +
geom_line(color = "red", size = 1) +
labs(title = "Fronteira Eficiente com Taxa Livre de Risco (CML)",
x = "Desvio Padrão do Portfólio",
y = "Retorno Esperado do Portfólio") +
theme_minimal() +
geom_point(aes(x = sigma_t, y = mu_t), color = "blue", size = 3) +
annotate("text", x = sigma_t, y = mu_t,
label = "Portfólio Tangência", vjust = -1)
}
})Fronteira Eficiente com 3 Ativos
Fronteira Eficiente
A seguir, definimos o gráfico que reage aos inputs definidos acima: