# 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("PLTR", "IBM", "BLK", "TSM", "SLB")
prices <- tq_get(x = symbols,
get = "stock.prices",
fro = "2020-12-31",
to = "2024-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", "returns"))
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "BLK" "IBM" "PLTR" "SLB" "TSM"
weights <- c(0.4, 0.2, 0.2, 0.1, 0.1)
weights
## [1] 0.4 0.2 0.2 0.1 0.1
w_tbl <- tibble(symbols, weights)
portfolio_returns_tbl <- asset_returns_tbl %>%
tq_portfolio(assets_col = asset,
returns_col = returns,
weights = w_tbl,
rebalance_on = "months")
portfolio_sd_tidyquant_builtin_percentage <- portfolio_returns_tbl %>%
tq_performance(Ra = portfolio.returns,
performance_fun = table.Stats) %>%
select(Stdev) %>%
mutate(tq_sd = round(Stdev, 4))
portfolio_sd_tidyquant_builtin_percentage
## # A tibble: 1 × 2
## Stdev tq_sd
## <dbl> <dbl>
## 1 0.0732 0.0732
portfolio_mean_tidyquant_builtin_percentage <- mean(portfolio_returns_tbl$portfolio.returns)
portfolio_mean_tidyquant_builtin_percentage
## [1] 0.01255651
sd_mean_tbl_Apply <- asset_returns_tbl %>%
group_by(asset) %>%
tq_performance(Ra = returns,
performance_fun = table.Stats) %>%
select(Mean = ArithmeticMean, Stdev) %>%
ungroup() %>%
add_row(tibble(asset = "Portfolio",
Mean = portfolio_mean_tidyquant_builtin_percentage,
Stdev = portfolio_sd_tidyquant_builtin_percentage$tq_sd))
sd_mean_tbl_Apply
## # A tibble: 6 × 3
## asset Mean Stdev
## <chr> <dbl> <dbl>
## 1 BLK 0.0083 0.0847
## 2 IBM 0.0183 0.064
## 3 PLTR 0.013 0.207
## 4 SLB 0.0169 0.112
## 5 TSM 0.013 0.0959
## 6 Portfolio 0.0126 0.0732
sd_mean_tbl_Apply %>%
ggplot(aes(x = Stdev, y = Mean)) +
geom_point() +
ggrepel::geom_text_repel(aes(label = asset))
I’d expect my portfolio to return less than most individual stocks in the portfolio, but not by much. With that being said, if the market were to under perform, I could expect my portfolio to take much less loss than if I were to invest individually in these stocks, given the low standard deviation. One stock I would invest all my money in, rather than the portfolio, is IBM. It has a much higher expected return, and hardly any risk associated with the standard deviation.