# Load packages

# Core
library(tidyverse)
library(tidyquant)

Goal

Visualize expected returns and risk to make it easier to compare the performance of multiple assets and portfolios.

Choose your stocks.

from 2012-12-31 to 2017-12-31

1 Import stock prices

symbols <- c("TSLA", "HD", "MSFT", "NKE")

prices <- tq_get(x = symbols,
get = "stock.prices",
from = "2012-12-31",
to = "2017-12-31")

2 Convert prices to returns (monthly)

asset_returns_tbl <- prices %>%

group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "quarterly",
type = "log") %>%
slice(-1) %>%
ungroup() %>%
set_names(c("asset", "date", "returns"))

3 Assign a weight to each asset (change the weigting scheme)

symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()

w <- c(0.30,
0.25,
0.20,
0.15)

w_tbl <- tibble(symbols, w)

4 Build a portfolio

portfolio_returns_rebalanced_monthly_tbl <- asset_returns_tbl %>%

tq_portfolio(assets_col = asset,
returns_col = returns,
weights = w_tbl,
col_rename = "returns",
rebalance_on = "quarters")

portfolio_returns_rebalanced_monthly_tbl
## # A tibble: 20 × 2
##    date        returns
##    <date>        <dbl>
##  1 2013-03-28  0.102  
##  2 2013-06-28  0.254  
##  3 2013-09-30  0.103  
##  4 2013-12-31  0.0361 
##  5 2014-03-31  0.0515 
##  6 2014-06-30  0.0462 
##  7 2014-09-30  0.0973 
##  8 2014-12-31  0.0464 
##  9 2015-03-31 -0.0218 
## 10 2015-06-30  0.0852 
## 11 2015-09-30  0.0302 
## 12 2015-12-31  0.0987 
## 13 2016-03-31 -0.00438
## 14 2016-06-30 -0.0618 
## 15 2016-09-30  0.0201 
## 16 2016-12-30  0.0352 
## 17 2017-03-31  0.104  
## 18 2017-06-30  0.0790 
## 19 2017-09-29  0.00782
## 20 2017-12-29  0.106
# write_rds(portfolio_returns_rebalanced_monthly_tbl,
#"00_data/Ch03_portfolio_returns_rebalanced_monthly_tbl.rds")

5 Compute Standard Deviation

portfolio_sd_tidyquant_builtin_percent <- portfolio_returns_rebalanced_monthly_tbl  %>%
    
    tq_performance(Ra = returns,
                   Rb = NULL,
                   performance_fun = table.Stats) %>%
    
    select(Stdev) %>%
    mutate(tq_sd = round(Stdev, 4))

portfolio_sd_tidyquant_builtin_percent
## # A tibble: 1 × 2
##    Stdev  tq_sd
##    <dbl>  <dbl>
## 1 0.0655 0.0655
# Mean of portfolio returns
portfolio_mean_tidyquant_builtin_percent <- mean(portfolio_returns_rebalanced_monthly_tbl$returns)

portfolio_mean_tidyquant_builtin_percent
## [1] 0.06070159