# 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
# Choose stocks
symbols <- c("AMZN", "NVDA", "WMT")
# Using tq_get() ----
prices <- tq_get(x = symbols,
get = "stock.prices",
from = "2012-12-31",
to = "2017-12-31")
asset_returns_tbl <- prices %>%
# Calculate monthly returns
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
type = "log") %>%
slice(-1) %>%
ungroup() %>%
# remane
set_names(c("asset", "date", "returns"))
# period_returns = c("yearly", "quarterly", "monthly", "weekly")
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
w <- c(0.25,
0.25,
0.20)
w_tbl <- tibble(symbols, w)
portfolio_returns_rebalanced_monthly_tbl <- asset_returns_tbl %>%
tq_portfolio(assets_col = asset,
returns_col = returns,
weights = w_tbl,
col_rename = "returns",
rebalance_on = "months")
portfolio_returns_rebalanced_monthly_tbl
## # A tibble: 60 × 2
## date returns
## <date> <dbl>
## 1 2013-01-31 0.0191
## 2 2013-02-28 0.0108
## 3 2013-03-28 0.0178
## 4 2013-04-30 0.0131
## 5 2013-05-31 0.0220
## 6 2013-06-28 -0.000717
## 7 2013-07-31 0.0364
## 8 2013-08-30 -0.0228
## 9 2013-09-30 0.0427
## 10 2013-10-31 0.0394
## # ℹ 50 more rows
portfolio_sd_tidyquant_builtin_percent <- portfolio_returns_rebalanced_monthly_tbl %>%
tq_performance(Ra = returns,
Rb = NULL,
performance_fun = table.Stats) %>%
select(Stdev) %>%
mutate(tq_sd = round(Stdev, 4))
portfolio_sd_tidyquant_builtin_percent
## # A tibble: 1 × 2
## Stdev tq_sd
## <dbl> <dbl>
## 1 0.0342 0.0342
# Mean of portfolio returns
portfolio_mean_tidyquant_builtin_percent <-
mean(portfolio_returns_rebalanced_monthly_tbl)
portfolio_mean_tidyquant_builtin_percent
## [1] NA
sd_mean_tbl <- asset_returns_tbl %>%
group_by(asset) %>%
tq_performance(Ra = returns,
performance_fun = table.Stats) %>%
select(Mean = ArithmeticMean, Stdev) %>%
ungroup() %>%
# Add portfolio sd
add_row(tibble(asset = "Portfolio",
Mean = portfolio_mean_tidyquant_builtin_percent,
Stdev = portfolio_sd_tidyquant_builtin_percent$tq_sd))
sd_mean_tbl
## # A tibble: 4 × 3
## asset Mean Stdev
## <chr> <dbl> <dbl>
## 1 AMZN 0.0257 0.0739
## 2 NVDA 0.0471 0.0881
## 3 WMT 0.0083 0.0471
## 4 Portfolio NA 0.0342
Some single stocks have the potential to give you a larger return compared to your portfolio, in this case NVDA has the highest standard deviation making them the best stock to choose from the ones selected. Sticks with higher expected returns had the potential for more risk, as NVDA with 0.0471 with the highest and WMT with the lowest at 0.0083. The safest choice is up to personal prefferance, in this case I would choose AMZN where it sits right in the middle between risk and return, giving you a strong return potential with minimal risk taken.