# Load packages
# Core
library(tidyverse)
library(tidyquant)
Collect individual returns into a portfolio by assigning a weight to each stock
two stocks: “TSLA”, “NKE”
from 2012-12-31 to 2017-12-31
symbols <- c("TSLA", "NKE")
prices <- tq_get(x = symbols,
get = "stock.prices",
from = "2012-12-31",
to = "2017-12-31")
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"))
# symbols
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "NKE" "TSLA"
# weights
weights <- c(0.50,0.50)
weights
## [1] 0.5 0.5
w_tbl <- tibble(symbols, weights)
w_tbl
## # A tibble: 2 × 2
## symbols weights
## <chr> <dbl>
## 1 NKE 0.5
## 2 TSLA 0.5
#?tq_portfolio
portfolio_returns_tbl <- asset_returns_tbl %>%
tq_portfolio(assets_col = asset,
returns_col = returns,
weights = w_tbl,
col_rename = "returns",
rebalance_on = "months")
portfolio_returns_tbl
## # A tibble: 60 × 2
## date returns
## <date> <dbl>
## 1 2013-01-31 0.0742
## 2 2013-02-28 -0.0313
## 3 2013-03-28 0.0822
## 4 2013-04-30 0.215
## 5 2013-05-31 0.283
## 6 2013-06-28 0.0630
## 7 2013-07-31 0.106
## 8 2013-08-30 0.116
## 9 2013-09-30 0.140
## 10 2013-10-31 -0.0739
## # ℹ 50 more rows
portfolio_skew_tidyquant_building_percent <- portfolio_returns_tbl %>%
tq_performance(Ra = returns,
performance_fun = table.Stats) %>%
select(Skewness)
portfolio_skew_tidyquant_building_percent
## # A tibble: 1 × 1
## Skewness
## <dbl>
## 1 0.700