I have an error with this code and I would like to ask for help. Thank you in advance.
symbols <- sort(c("SPY","VGT","EFA","DBC","AGG"))
prices <-
getSymbols(symbols, src = 'yahoo', from = "2013-01-01",
auto.assign = TRUE, warnings = FALSE) %>%
map(~Cl(get(.))) %>%
reduce(merge) %>%
`colnames<-`(symbols)
# Get monthly returns.
portfolio_component_monthly_returns_xts <-
prices %>%
# Convert to tibble so can stay in the tidyquant/verse.
as_tibble(preserve_row_names = TRUE) %>%
# Add a date column.
mutate(date = ymd(row.names)) %>%
# Remove the row.names column
select(-row.names) %>%
# Have the date column as the first column.
select(date, everything()) %>%
# Gather into long format in order to use tq_transmute().
gather(asset, return, -date) %>%
group_by(asset) %>%
# Use the function from tidyquant; note how easily we could change to
# a different time period like weekly or yearly.
tq_transmute(mutate_fun = periodReturn, period = "monthly") %>%
# Put the results back to wide format.
spread(asset, monthly.returns) %>%
# Convert back to an xts, so we can use the cov() and StdDev() functions.
as_xts(date_col = date)
head(portfolio_component_monthly_returns_xts)
library(quantmod)
library(tidyquant)
library(lubridate)
library(tidyverse)
library(timetk) # had to add
symbols <- sort(c("SPY","VGT","EFA","DBC","AGG"))
prices <-
getSymbols(symbols, src = 'yahoo', from = "2013-01-01",
auto.assign = TRUE, warnings = FALSE) %>%
map(~Cl(get(.))) %>%
reduce(merge) %>%
`colnames<-`(symbols)
# Get monthly returns.
portfolio_component_monthly_returns <-
prices %>%
# Convert to tibble so can stay in the tidyquant/verse.
as_tibble(rownames = "row.names") %>%
# Add a date column.
mutate(date = ymd(row.names)) %>%
# Remove the row.names column
select(-row.names) %>%
# Have the date column as the first column.
select(date, everything()) %>%
# Gather into long format in order to use tq_transmute().
gather(asset, return, -date) %>%
group_by(asset) %>%
# Use the function from tidyquant; note how easily we could change to
# a different time period like weekly or yearly.
tq_transmute(mutate_fun = periodReturn, period = "monthly") %>%
# Put the results back to wide format.
spread(asset, monthly.returns)
portfolio_component_monthly_returns_xts <-
portfolio_component_monthly_returns %>%
# Convert back to an xts, so we can use the cov() and StdDev() functions.
tk_xts()
head(portfolio_component_monthly_returns_xts)