# Load packages
# Core
library(tidyverse)
library(tidyquant)
Visualize expected returns and risk to make it easier to compare the performance of multiple assets and portfolios.
Choose your stocks.
from 2012-12-31 to 2017-12-31
symbols <- c("NKE", "TSLA", "NVDA", "GOOGL", "ADDYY")
prices <- tq_get(x = symbols,
get = "stock.prices",
from = "2025-12-31",
to = "2026-12-31")
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", "return"))
# symbols
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "ADDYY" "GOOGL" "NKE" "NVDA" "TSLA"
#weights
weights <- c(0.25, 0.25, 0.2, 0.2, 0.1)
weights
## [1] 0.25 0.25 0.20 0.20 0.10
w_tbl <- tibble(symbols, weights)
portfolio_returns_tbl <- asset_returns_tbl %>%
tq_portfolio(assets_col = asset,
returns_col = return,
weights = w_tbl,
rebalace_on = "months")
portfolio_returns_tbl
## # A tibble: 10 × 2
## date portfolio.returns
## <date> <dbl>
## 1 2026-01-30 -0.0144
## 2 2026-02-27 -0.0310
## 3 2026-03-31 -0.100
## 4 2026-04-30 0.0931
## 5 2026-05-29 0.0575
## 6 2026-06-30 -0.0358
## 7 2026-07-31 -0.0551
## 8 2026-08-31 -0.00268
## 9 2026-09-30 -0.0174
## 10 2026-10-19 0.0129
portfolio_sd_tidyquant_builtin_percent <- portfolio_returns_tbl %>%
tq_performance(Ra = portfolio.returns,
performance_fun = table.Stats) %>%
select(Stdev) %>%
mutate(tq_sd = round(Stdev, 4))
portfolio_sd_tidyquant_builtin_percent * 100
## Stdev tq_sd
## 1 5.49 5.49
# Mean of portfolio returns
portfolio_sd_tidyquant_builtin_percent <- mean(portfolio_returns_tbl$portfolio.returns)
portfolio_sd_tidyquant_builtin_percent
## [1] -0.009310733
# Expected Returns vs Risk
sd_mean_tbl <- asset_returns_tbl %>%
group_by(asset) %>%
tq_performance(Ra = return,
performance_fun = table.Stats) %>%
select(Mean = ArithmeticMean, Stdev) %>%
ungroup() %>%
# Add portfolio Sd
add_row(tibble(asset = "Portfolio" ,
Mean = portfolio_sd_tidyquant_builtin_percent,
Stdev = sd(portfolio_returns_tbl$portfolio.returns)))
sd_mean_tbl
## # A tibble: 6 × 3
## asset Mean Stdev
## <chr> <dbl> <dbl>
## 1 ADDYY -0.0096 0.0985
## 2 GOOGL 0.0098 0.110
## 3 NKE -0.0516 0.0799
## 4 NVDA 0.0159 0.0672
## 5 TSLA -0.02 0.129
## 6 Portfolio -0.00931 0.0549
How should you expect your portfolio to perform relative to its
assets in the portfolio? Would you invest all your money in any of the
individual stocks instead of the portfolio? Discuss both in terms of
expected return and risk.
My diversified portfolio balances the weighted average of individual
returns with lower overall risk, whereas investing in a single stock
exposes me to much higher volatility for potentially extreme outcomes.
Therefore, the portfolio provides a safer, more balanced risk-return
trade-off compared to the high risk of putting all my money into just
one stock.