# 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("AAPL", "GOOG", "NFLX", "VOO")
prices <- tq_get(x =     symbols, 
                 get =   "stock.prices",
                 from =  "2019-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] "AAPL" "GOOG" "NFLX" "VOO"
# weights
weights <- c(.3, .3, .2, .2)
weights
## [1] 0.3 0.3 0.2 0.2
w_tbl <- tibble(symbols, weights)
w_tbl
## # A tibble: 4 × 2
##   symbols weights
##   <chr>     <dbl>
## 1 AAPL        0.3
## 2 GOOG        0.3
## 3 NFLX        0.2
## 4 VOO         0.2

4 Build a portfolio

# ?tq_portfolio

portfolio_returns_tbl <- asset_returns_tbl %>%
    
    tq_portfolio(assets_col = asset,
                 returns_col = returns,
                 weights = w_tbl,
                 rebalance_on = "months")
portfolio_returns_tbl
## # A tibble: 28 × 2
##    date       portfolio.returns
##    <date>                 <dbl>
##  1 2020-03-31           -0.0981
##  2 2020-06-30            0.243 
##  3 2020-09-30            0.120 
##  4 2020-12-31            0.133 
##  5 2021-03-31            0.0306
##  6 2021-06-30            0.111 
##  7 2021-09-30            0.0587
##  8 2021-12-31            0.112 
##  9 2022-03-31           -0.120 
## 10 2022-06-30           -0.334 
## # ℹ 18 more rows

5 Plot: Portfolio Histogram and Density

portfolio_returns_tbl %>%
     ggplot(mapping = aes(x = portfolio.returns)) + 
    geom_histogram(fill = "cornflowerblue",
                   binwidth = .01,) +
    geom_density() +
    
        # Formatting
    labs(x = "returns",
        title = "Portfolio Histogram + Density, 2020 - Present",
        y = "Distribution") +
   
    scale_x_continuous(labels = scales::percent)

What return should you expect from the portfolio in a typical quarter? A typical return for this portfolio may be around 10% in a quarter. The majority of the distribution ranges from -13% to 27%, so it may be a volatile investment.