The error message suggests that log_returns - the object you are trying to access with the $ operator - is an atomic vector. Atomic vectors in R (like numeric, character, or logical vectors) do not support the $ operator because they are essentially one-dimensional arrays without names for their elements. The $ operator is used to extract elements by name from lists or data frames, not vectors.
Given your code is expecting log_returns to be a structure that can contain both asset names (Asset) and presumably their log returns, I suspect log_returns should be a data frame or a similar structure (like a tibble, if you're using the tidyverse) where one column is named Asset and the other columns represent different data related to these assets (e.g., their log returns over time).
If log_returns is currently an atomic vector and does not actually contain the necessary structure to execute your code (i.e., if you mistakenly thought it was a data frame), you need to obtain or construct the appropriate data frame with asset names and their log returns. Without knowing the exact structure or source of your log_returns, here is a generic example of how you might structure your data frame:
r
# Example of creating a simulated log_returns data frame
assets <- c(rep("T", 3), rep("PFE", 3), rep("XAU", 3), rep("GOOGL", 3), rep("USDINR", 3), rep("EURUSD", 3), rep("NG", 3))
dates <- rep(seq(as.Date("2023-01-01"), by="day", length.out=3), 7) # Example dates
log_returns_sample <- runif(21, min=-0.05, max=0.05) # Simulate some log return values
log_returns <- data.frame(
Date = dates,
Asset = assets,
LogReturn = log_returns_sample
)
# Select assets for Strategy 1
strategy1_assets <- c("T", "PFE", "XAU", "GOOGL", "USDINR")
strategy1_selection <- log_returns[log_returns$Asset %in% strategy1_assets, ]
# Select assets for Strategy 2
strategy2_assets <- c("EURUSD", "NG", "PFE", "GOOGL", "T")
strategy2_selection <- log_returns[log_returns$Asset %in% strategy2_assets, ]
# ... rest of your code for portfolio optimization using PortfolioAnalytics
This is just an illustrative example to create a data frame called log_returns. You would need to replace the simulated data here with your actual log return data, ensuring there's a column named Asset and other relevant columns (such as log returns on specific dates) for your analysis. Make sure your log_returns object is properly constructed as a data frame before attempting to filter it with the $ operator and creating subsets for your strategies.