# 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("NFLX","AAPL", "TSLA")
prices <- tq_get(x = symbols,
                 get = "stock.prices",
                 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     = "monthly",
                 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()
symbols
## [1] "AAPL" "NFLX" "TSLA"
weights <- c(.33,.33,.33)
weights
## [1] 0.33 0.33 0.33
w_tble <- tibble(symbols, weights)
w_tble
## # A tibble: 3 × 2
##   symbols weights
##   <chr>     <dbl>
## 1 AAPL       0.33
## 2 NFLX       0.33
## 3 TSLA       0.33

4 Build a portfolio

portfolio_returns_tbl <- asset_returns_tbl %>%
    
    tq_portfolio(assets_col = asset, 
                 returns_col = returns,
                 weights = w_tble, 
                 rebalance_on ="months")

portfolio_returns_tbl
## # A tibble: 60 × 2
##    date       portfolio.returns
##    <date>                 <dbl>
##  1 2013-01-31           0.173  
##  2 2013-02-28           0.00981
##  3 2013-03-28           0.0308 
##  4 2013-04-30           0.161  
##  5 2013-05-31           0.218  
##  6 2013-06-28          -0.0335 
##  7 2013-07-31           0.166  
##  8 2013-08-30           0.152  
##  9 2013-09-30           0.0655 
## 10 2013-10-31          -0.0184 
## # … with 50 more rows

5 Plot: Portfolio Histogram and Density

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

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