I have adapted to R a python code to plot these charts:
I simulate the regression lines with x_plot <- seq(min(market_excess_return), max(market_excess_return), length.out = 100)
However, when I plot the regression lines to include them in the chart I am capable to include only one fitted line with geom_abline()
, resulting this:
How can I include the x_plot
object?
I provide the full code:
library(ggplot2)
library(dplyr)
library(brms) # For Bayesian regression
library(bayesplot) # For plotting Bayesian analysis results
set.seed(42)
size <- 200
Rf <- 0.02
ERm <- 0.1
beta <- 1.5
sigma <- 0.05
ERm_samples <- rnorm(size, ERm, sigma)
epsilon <- rnorm(size, 0, sigma)
ERi_samples <- Rf + beta * (ERm_samples - Rf) + epsilon
market_excess_return <- ERm_samples - Rf
asset_excess_return <- ERi_samples - Rf
data_capm <- data.frame(market_excess_return=market_excess_return, asset_excess_return=asset_excess_return)
ggplot(data_capm, aes(x=market_excess_return, y=asset_excess_return)) +
geom_point(aes(color='Sampled Data')) +
labs(x='Market Excess Return', y='Asset Excess Return', title='Generated CAPM Data') +
theme_minimal()
# Bayesian regression using brms
model_capm <- brm(asset_excess_return ~ market_excess_return, data = data_capm,
family = gaussian(), prior = c(
prior(normal(0, 20), class = Intercept),
prior(normal(0, 20), class = b),
prior(cauchy(0, 10), class = sigma)
))
# Plotting the trace
trace_capm <- as.mcmc(model_capm)
bayesplot::mcmc_trace(trace_capm)
# Posterior predictive checks
#posterior_intercept <- fitted(model_capm)$Estimate[1,]
#posterior_slope <- fitted(model_capm)$Estimate[2,]
posterior_intercept <- fitted(model_capm)[1, "Estimate"]
posterior_slope <- fitted(model_capm)[2, "Estimate"]
x_plot <- seq(min(market_excess_return), max(market_excess_return), length.out = 100)
ggplot(data_capm, aes(x=market_excess_return, y=asset_excess_return)) +
geom_point(alpha=0.5, color = 'tomato') +
geom_abline(intercept=mean(posterior_intercept),
slope=mean(posterior_slope),
color="blue",
linetype="dashed") +
labs(x='Market Excess Return',
y='Asset Excess Return',
title='Posterior Predictive Regression Lines with Observed Data') +
theme_minimal()