# Load packages

# Core
library(tidyverse)
library(tidyquant)

Goal

Collect individual returns into a portfolio by assigning a weight to each stock

Choose your stocks.

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

1 Import stock prices

symbols <- c("HMC", "WMT", "TGT")

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

2 Convert prices to returns (quarterly)

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
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "HMC" "TGT" "WMT"
# weights 
weight <- c(0.25, 0.25, 0.5)
weight
## [1] 0.25 0.25 0.50
w_tbl <- tibble(symbols, weight)
w_tbl
## # A tibble: 3 × 2
##   symbols weight
##   <chr>    <dbl>
## 1 HMC       0.25
## 2 TGT       0.25
## 3 WMT       0.5

4 Build a portfolio

# ?tq_portfolio

portfolio_returns_tbl <- asset_returns_tbl %>%
    
    tq_portfolio(assets_col  = asset, 
                 returns_col = returns, 
                 weights     = w_tbl, 
                 reblance_on = "quarter")

portfolio_returns_tbl
## # A tibble: 20 × 2
##    date       portfolio.returns
##    <date>                 <dbl>
##  1 2013-03-28          0.0972  
##  2 2013-06-28         -0.00143 
##  3 2013-09-30         -0.0118  
##  4 2013-12-31          0.0538  
##  5 2014-03-31         -0.0595  
##  6 2014-06-30         -0.0161  
##  7 2014-09-30          0.0306  
##  8 2014-12-31          0.0838  
##  9 2015-03-31          0.0215  
## 10 2015-06-30         -0.0755  
## 11 2015-09-30         -0.0645  
## 12 2015-12-31         -0.0337  
## 13 2016-03-31          0.0656  
## 14 2016-06-30         -0.0298  
## 15 2016-09-30          0.0173  
## 16 2016-12-30          0.00102 
## 17 2017-03-31         -0.0457  
## 18 2017-06-30          0.000517
## 19 2017-09-29          0.0663  
## 20 2017-12-29          0.192

5 Plot: Portfolio Histogram and Density

portfolio_returns_tbl %>% 
    
    ggplot(mapping = aes(x = portfolio.returns)) + 
    geom_histogram(fill = "red", binwidth = 0.01) +
    geom_density() +
    
    #Formatting 
    scale_x_continuous(labels = scales::percent_format()) +
    
    labs(x     = "returns",
         y     = "distribution",
         title = "Portfolio Histogram and Density")

What return should you expect from the portfolio in a typical quarter?

The density curve we created is the highest between -6% and 8%. This is because that’s where the most values are located. This histogram is in between a right skewed chart and no skew. I would expect a typical return would fall around the distribution of 2, considering that’s where most vales are located between -6% and 8%.