I know there are good resources for calculating stock and portfolio returns using performance analytics in tidyquant for R. For example, assume we want to determine the annual portfolio returns (2011 through 2015) for a portfolio that contains "XOM" (0.5), "MA" (0.3), and "GOOG" (0.2), where () indicates the asset weight within the portfolio. The code would simply be:
Ra_symbols <- c("XOM", "MA", "GOOG")
wts_map <- tibble(
symbols = c("XOM", "MA", "GOOG"),
weights = c(0.5, 0.3, 0.2)
)
Ra_2010to2020 <- Ra_symbols %>%
tq_get(get = "stock.prices",
from = "2010-12-31",
to = "2015-12-31") %>%
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "yearly",
col_rename = "Ra")
Ra_weightedportfolioreturn <- Ra_2010to2020 %>%
tq_portfolio(assets_col = symbol,
returns_col = Ra,
weights = wts_map,
col_rename = "Ra_using_wts_map")
But I cannot find any resource to help with the code if the portfolio contains different assets in each year with varying weights. For example, assume we have two dataframes: one with the symbols for each year and one with the respective portfolio weights. Below is the code to read in the csv file with the symbols and weights, along with images to illustrate the dataframes.
symbols2011to2015 <- read_csv("Symboltest_2011to2015.csv")
weights2011to2015 <- read_csv("wtstest_2011to2015.csv")
I'm thinking it's going to involve some tidyverse functions like "apply" or "map", but am not sure. Also, can tidyquant work with symbols (and weights) in a dataframe as I have it, or do I need to convert them to character values similar to the results from c("XOM", "MA", "GOOG")? Eventually, I'd like to expand this concept for monthly periods, but once I figure it out for multiple years the process should be similar.
Any help would be much appreciated!