Estimating returns based on returns prior to each respective event_date using lm() and saving the estimates

I plan to estimate returns using the following code but I obtain no results.

The idea is to based it on returns and benchmark return for each coin_name prior to the event_date.

Data structure looks like:

# Assuming your data frame is named "data"
data <- data %>%
  mutate(
    returns = as.numeric(gsub(",", ".", returns)),
    benchmark_returns_bitcoin = as.numeric(gsub(",", ".", benchmark_returns_bitcoin)),
    event_date = as.Date(event_date, format = "%m/%d/%Y")
  )

# Filter the data to include only event markers
filtered_data <- data %>%
  filter(event_marker == 1)

# Function to estimate returns based on linear regression
estimate_returns <- function(data) {
  if (nrow(data) < 11) {
    return(NA_real_)
  }
  mod <- lm(returns ~ benchmark_returns_bitcoin, data = data)
  predict(mod, newdata = tail(data, 1))  # Predict based on the last row
}

# Apply the function to each group of coin_name and event_date
result <- filtered_data %>%
  group_by(coin_name, event_date) %>%
  arrange(date) %>%
  mutate(estimated_returns = rollapply(data.frame(data), width = 11, FUN = estimate_returns, by.column = FALSE, align = "right")) %>%
  ungroup()

# View the results
View(result)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.