# 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("NVDA", "INTC", "GOOG", "AMD", "AAPL")
prices <- tq_get(x = symbols, 
                 get = "stock.prices",
                 from = "2012-12-31",
                 to   = "2027-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 <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "AAPL" "AMD"  "GOOG" "INTC" "NVDA"
#"NVDA" "INTC" "GOOG" "AMD" "AAPL"
weights <- c(0.20, 0.15, 0.15, 0.30, 0.25)
weights 
## [1] 0.20 0.15 0.15 0.30 0.25
# 0.20 0.15 0.15 0.30 0.25
 w_tbl <- tibble(symbols, weights)
w_tbl 
## # A tibble: 5 × 2
##   symbols weights
##   <chr>     <dbl>
## 1 AAPL       0.2 
## 2 AMD        0.15
## 3 GOOG       0.15
## 4 INTC       0.3 
## 5 NVDA       0.25

##4 Build a portfolio

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

portfolio_returns_tbl 
## # A tibble: 52 × 2
##    date       portfolio.returns
##    <date>                 <dbl>
##  1 2013-03-28          0.0241  
##  2 2013-06-28          0.123   
##  3 2013-09-30          0.0403  
##  4 2013-12-31          0.122   
##  5 2014-03-31          0.0270  
##  6 2014-06-30          0.117   
##  7 2014-09-30          0.0245  
##  8 2014-12-31          0.00478 
##  9 2015-03-31          0.000522
## 10 2015-06-30         -0.0364  
## # ℹ 42 more rows

##5 Plot: Portfolio Histogram and Density

portfolio_returns_tbl %>%
    
    ggplot(mapping = aes(x = portfolio.returns)) +
    geom_histogram(fill = "cornflowerblue", binwidth = 0.01) +
    # This creates the blue form/graph
     geom_density() +
    # This creates the line
   
     # 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? With my returns ranging from -40% to 40% I should expect around -5% and 23% returns on my portfolio as that is the highest distribution area and has a spike of density in those markers as shown in the curve of the plot. I can also expect to have a positive return more often than not as there is more distribution above the 0% on the graph showing a typical return of around 10 percent on average.