# Load packages
# 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("CRWD", "AMZN", "SHOP","TTD", "NVDA")
prices <- tq_get(x = symbols,
get = "stock.prices",
from = "2021-01-01")
asset_returns_tbl <- prices %>%
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
type = "log") %>%
slice(-1) %>%
ungroup() %>%
set_names(c("asset", "date", "returns"))
# symbols
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "AMZN" "CRWD" "NVDA" "SHOP" "TTD"
# weights
weights <- c(0.25, 0.25, 0.2, 0.2, 0.1)
w_tbl <- tibble(symbols, weights)
w_tbl
## # A tibble: 5 × 2
## symbols weights
## <chr> <dbl>
## 1 AMZN 0.25
## 2 CRWD 0.25
## 3 NVDA 0.2
## 4 SHOP 0.2
## 5 TTD 0.1
# ?tq_portfolio
portfolio_returns_tbl <- asset_returns_tbl %>%
tq_portfolio(assets_col = asset,
returns_col = returns,
weights = w_tbl,
rebalance_on = "months",
col_rename = "returns")
portfolio_returns_tbl
## # A tibble: 46 × 2
## date returns
## <date> <dbl>
## 1 2021-02-26 0.0378
## 2 2021-03-31 -0.0978
## 3 2021-04-30 0.110
## 4 2021-05-28 0.00183
## 5 2021-06-30 0.149
## 6 2021-07-30 -0.000161
## 7 2021-08-31 0.0648
## 8 2021-09-30 -0.0992
## 9 2021-10-29 0.105
## 10 2021-11-30 0.0333
## # ℹ 36 more rows
market_returns_tbl <- tq_get(x = "SPY",
get = "stock.prices",
from = "2021-01-01") %>%
# Convert prices to returns
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
type = "log",
col_rename = "returns") %>%
slice(-1)
portfolio_market_returns_tbl <- left_join(market_returns_tbl,
portfolio_returns_tbl,
by = "date") %>%
set_names("date", "market_returns", "portfolio_returns")
portfolio_market_returns_tbl %>%
tq_performance(Ra = portfolio_returns,
Rb = market_returns,
performance_fun = CAPM.beta)
## # A tibble: 1 × 1
## CAPM.beta.1
## <dbl>
## 1 1.66
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 = tidyquant::palette_light()[3]) +
labs(y = "Portfolio returns",
x = "Market returns")
How sensitive is your portfolio to the market? Discuss in terms of the beta coefficient. Does the plot confirm the beta coefficient you calculated?
My portfolio does follow the market due to the positive beta, but it is more volatile than the market is. My portfolio is very sensitive to the market, my beta coefficient is 1.66, so when the market increases by 10% my portfolio would increases by 16.6%. The plot does confirm this, showing around a 16 percent loss and gain when the market would have a 10 percent loss or gain. My spread of points is not perfect, but is still pretty good. Most points are close to the line, and there are only a few big outliars.