SOLVED
I'm working on replication of the code that is used at the Reproducible Finance with R. A link to the webinar is here: https://www.rstudio.com/resources/webinars/reproducible-finance-with-r/
The data for the exercise was downloaded from Yahoo Finance. The .csv file is here: http://www.reproduciblefinance.com/data/data-download/
Following the instructions provided at the webinar, it happened to me that the code doesn't work as it is in the lesson:
portfolio_returns_tidyquant_rebalanced_monthly %>%
mutate(
dplyr_port_returns = portfolio_returns_dplyr_byhand$returns,
xts_port_returns = coredata(portfolio_returns_xts_rebalanced_monthly)
)%>%
head()
The system doesn't provide any output, nor it shows if there is a mistake in the code.
I then decided to eliminate each new variable I want to create to see if something happens. It turned out that if one variable is not included in the mutate() command the system produces a partial output I need. Below are a code and an output.
portfolio_returns_tidyquant_rebalanced_monthly %>%
mutate(
dplyr_port_returns = portfolio_returns_dplyr_byhand$returns,
# xts_port_returns = coredata(portfolio_returns_xts_rebalanced_monthly)
)%>%
head(2)
Date | returns | dplyr_port_returns |
---|---|---|
2013-01-31 | 0.0308487341 | 0.0308487341 |
2013-02-28 | -0.0008697461 | -0.0008697461 |
In addition, some information about variables:
class(portfolio_returns_xts_rebalanced_monthly)
[1] "xts" "zoo"
class(portfolio_returns_dplyr_byhand)
[1] "tbl_df" "tbl" "data.frame"
The portfolio_returns_xts_rebalanced_monthly
was created using the following code:
symbols <- c("SPY", "EFA", "IJS", "EEM", "AGG")
prices <-
getSymbols(
symbols,
src = 'yahoo',
from = "2012-12-31",
to = "2017-12-31",
auto.assign = T,
warnings = F
) %>%
map(~Ad(get(.))) %>%
reduce(merge) %>%
`colnames<-`(symbols)
w <- c(
0.25,
0.25,
0.20,
0.20,
0.10
)
prices_monthly <-
to.monthly(
prices,
indexAt = "lastof",
OHLC = FALSE
)
assets_return_xts <- na.omit(
Return.calculate(
prices_monthly,
method = "log"
)
)
portfolio_returns_xts_rebalanced_monthly <-
Return.portfolio(
assets_return_xts,
weights = w,
rebalance_on = 'months'
) %>%
`colnames<-`("returns")
I'm pretty sure this is somehow connected to a mutate() function and classes of variables, but I couldn't find any information on the matter. Your support is highly appreciated.
UPDATE.
Changing the class of one object from xts
to data.frame
, and adjusting a code a bit solved the issue.
An updated code:
portfolio_returns_xts_rebalanced_monthly_df <-
data.frame(
date=index(portfolio_returns_xts_rebalanced_monthly),
coredata(portfolio_returns_xts_rebalanced_monthly)
)
portfolio_returns_tidyquant_rebalanced_monthly %>%
mutate(
dplyr_port_returns = portfolio_returns_dplyr_byhand$returns,
xts_port_returns = portfolio_returns_xts_rebalanced_monthly_df$returns
)%>%
head()