# Load packages

# Core
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.3.6      ✔ purrr   0.3.4 
## ✔ tibble  3.1.8      ✔ dplyr   1.0.10
## ✔ tidyr   1.2.0      ✔ stringr 1.4.1 
## ✔ readr   2.1.2      ✔ forcats 0.5.2 
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
library(tidyquant)
## Loading required package: lubridate
## 
## Attaching package: 'lubridate'
## 
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
## 
## Loading required package: PerformanceAnalytics
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## 
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## 
## 
## Attaching package: 'xts'
## 
## The following objects are masked from 'package:dplyr':
## 
##     first, last
## 
## 
## Attaching package: 'PerformanceAnalytics'
## 
## The following object is masked from 'package:graphics':
## 
##     legend
## 
## Loading required package: quantmod
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo

##Goal Calculate and visualize your portfolio’s beta.

Choose your stocks and the baseline market.

from 2012-12-31 to present

1 Import stock prices

symbol <- c("BIG", "TSLA", "AMZN", "WM", "PLUG")

prices <- tq_get(x = symbol,
                 get = "stock.prices",
                 from = "2012-12-31",
                 to = "2022-12-4")

2 Convert prices to returns

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"))
##     asset      date   returns 
##   "asset"    "date" "returns"

3 Assign a weight to each asset

symbols <- asset_returns_tbl %>% distinct(symbol) %>% pull()
symbols
## [1] "AMZN" "BIG"  "PLUG" "TSLA" "WM"
weight <- c(0.2,0.2,0.2,0.2,0.2)
weight
## [1] 0.2 0.2 0.2 0.2 0.2
w_tbl <- tibble(symbols, weight)

4 Build a portfolio

portfolio_returns_tbl <- asset_returns_tbl %>%
    tq_portfolio(assets_col = symbol,
                 returns_col = monthly.returns,
                 weights = w_tbl,
                 rebalance_on = "months",
                 col_rename = "returns")
## Warning: `spread_()` was deprecated in tidyr 1.2.0.
## Please use `spread()` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was generated.

5 Compute CAPM Beta

Get Market Returns

market_returns_tbl <- tq_get(x    = "SPY",
                 get  = "stock.prices",
                 from = "2012-12-31",
                 to   = "2022-12-4")  %>%
    
    # Convert Prices to Monthly Returns
    tq_transmute(select     = adjusted, 
                 mutate_fun = periodReturn,
                 period     = "monthly",
                 type       = "log", 
                 col_rename = "returns") %>%
    slice(-1)

Join Returns

portfolio_market_returns_tbl <- left_join(market_returns_tbl, portfolio_returns_tbl, by = "date") %>%
    set_names("date", "market_returns", "portfolio_returns")

CAPM Beta

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.33

##6 Plot Scatter plot of Returns with Regression Line

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")
## `geom_smooth()` using formula 'y ~ x'

How sensitive is your portfolio to the market? Discuss in terms of the beta coefficient. Does the plot confirm the beta coefficient you calculated? Beta Coefficient is 1.146. The portfolio is decently sensitive to the market . Any amount with .25 of a 1 beta is reliant on the markets as they are a slightly more volatile reflection in times of loss they will lose slightly more and in times of growth they will grow slightly more. the plot is reflective of what I already knew.