# Load packages

# Core
library(tidyverse)
library(tidyquant)

Goal

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

five stocks: “SPY”, “EFA”, “IJS”, “EEM”, “AGG”

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

1 Import stock prices

symbols <- c("AAPL", "MSFT", "TSLA")

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

2 Convert prices to returns

asset_returns_tbl <- prices %>%
  group_by(symbol) %>%
  tq_transmute(
    select     = adjusted,
    mutate_fun = periodReturn,
        period     = "quarterly",
    type       = "log"
  ) %>%
  slice(-1) %>%  # remove first row of each group
  rename(returns = quarterly.returns)

3 Assign a weight to each asset

# Get unique stock symbols from asset_returns_tbl
symbols <- asset_returns_tbl %>%
  distinct(symbol) %>%
  pull()

# Assign custom weights 
weights <- c(0.4,0.4,0.2)

# Create weights table
w_tbl <- tibble(symbol = symbols, weights = weights)

4 Build a portfolio

portfolio_returns_tbl <- asset_returns_tbl %>%
  tq_portfolio(
    assets_col   = symbol,
    returns_col  = returns,
    weights      = w_tbl,
    col_rename   = "portfolio.returns",
    rebalance_on = "months"
  )

5 Plot

Scatter Plot of returns over Time

portfolio_returns_tbl %>%
  ggplot(aes(x = date, y = portfolio.returns)) +
  geom_point(color = "cornflowerblue") +
  labs(title = "Portfolio Returns: Scatter Plot",
       x = "Date", y = "Monthly Return")

Histogram of Returns

portfolio_returns_tbl %>%
  ggplot(aes(x = portfolio.returns)) +
  geom_histogram(fill = "cornflowerblue", binwidth = 0.005) +
  labs(title = "Portfolio Returns: Histogram",
       x = "Monthly Return", y = "Frequency")

Histogram with Density Plot

portfolio_returns_tbl %>%
  ggplot(aes(x = portfolio.returns)) +
  geom_histogram(aes(y = ..density..), fill = "cornflowerblue", binwidth = 0.01) +
  geom_density(color = "darkblue", size = 1) +
  labs(title = "Portfolio Returns: Histogram + Density",
       x = "Monthly Return", y = "Density")

Conclusion

In a typical quarter, I expect my portfolio to return between -5% and 10%. Based on the histogram and density plot, the distribution appears slightly right skewed, and the bulk of the returns fall within the range of -2% to 6%. The average quarterly return appears to be around 3.5%.