# Load packages
library(moments)
library(ggrepel)
library(scales)
library(stringr)
library(timetk)
library(PerformanceAnalytics)
# Core
library(tidyverse)
library(tidyquant)
Calculate and visualize your portfolio’s beta.
Choose your stocks and the baseline market.
from 2012-12-31 to present
symbols <- c("NVDA", "V", "META", "MSFT", "NFLX", "AVGO")
prices <- tq_get(
x = symbols,
get = "stock.prices",
from = "2012-12-31",
to = "2022-12-31"
)
returns_tbl <- prices %>%
group_by(symbol) %>%
tq_transmute(
select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
type = "log"
) %>%
ungroup()
weights <- c(0.15, 0.15, 0.2, 0.2, 0.15, 0.15) # Custom weights
portfolio_returns_tbl <- returns_tbl %>%
tq_portfolio(
assets_col = symbol,
returns_col = monthly.returns,
weights = weights,
col_rename = "returns"
)
market_returns_tbl <- tq_get("^IXIC",
from = "2012-12-31",
to = "2022-12-31") %>%
tq_transmute(
select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
type = "log"
) %>%
slice(-1) %>%
rename(returns = monthly.returns)
portfolio_market_returns_tbl <- left_join(
market_returns_tbl,
portfolio_returns_tbl,
by = "date"
) %>%
rename(
market_returns = returns.x,
portfolio_returns = returns.y
)
portfolio_xts <- portfolio_market_returns_tbl %>%
select(date, portfolio_returns) %>%
tk_xts(date_var = date)
market_xts <- portfolio_market_returns_tbl %>%
select(date, market_returns) %>%
tk_xts(date_var = date)
capm_beta <- CAPM.beta(Ra = portfolio_xts, Rb = market_xts)
capm_beta
## [1] 1.251999
portfolio_market_returns_tbl %>%
ggplot(aes(x = market_returns, y = portfolio_returns)) +
geom_point(color = "cornflowerblue") +
geom_smooth(method = "lm", se = FALSE, size = 1.5, color = palette_light()[[3]]) +
labs(
x = "Market Returns (NASDAQ)",
y = "Portfolio Returns",
title = "CAPM Scatterplot: Portfolio vs. NASDAQ"
)
How sensitive is your portfolio to the market? Discuss in terms of the beta coefficient. Does the plot confirm the beta coefficient you calculated?
The beta coefficient for my portfolio was 1.251999. Since the value is greater than 1, it means my portfolio is more volatile than the NASDAQ market, meaning it tends to mean big market movements. The positive beta confirms the portfolio moves in the same direction as the market. The scatterplot supports this interpretation: most of the data points cluster closely around the regression line, showing a strong linear relationship between market and portfolio returns.