R语言滚动回归仅获单个Beta系数问题排查求助
Hey there! Let's dig into why your rolling regression is spitting out a single full-period coefficient instead of daily results with a 10-day window. Here are the most common mistakes and fixes to get you back on track:
1. You're using a standard lm() instead of a rolling calculation function
Running a plain lm(v1 ~ v2, data = mydatareturns) will always fit a single model to your entire dataset. To do rolling regression, you need tools designed for sliding window calculations—like rollapply from the zoo package, roll_regres from the rollRegres package, or slide_dfr from the slider package.
Example with zoo::rollapply:
First, make sure your data is sorted by date (critical for correct windowing!) and formatted as a time series object:
library(zoo) # Step 1: Sort data by date (skip if already sorted) mydatareturns <- mydatareturns[order(mydatareturns$date), ] # Step 2: Convert to zoo object (ties data to dates) mydata_zoo <- zoo(mydatareturns[, c("v1", "v2")], order.by = mydatareturns$date) # Step 3: Define a function to extract regression coefficients from each window get_coefs <- function(window_data) { model <- lm(v1 ~ v2, data = as.data.frame(window_data)) return(coef(model)) # Returns intercept and v2 beta } # Step 4: Run rolling regression with 10-day window, aligned to the right (latest day in window) rolling_results <- rollapply( data = mydata_zoo, width = 10, FUN = get_coefs, by.column = FALSE, # Pass the entire window data frame to the function align = "right" ) # Convert results back to a data frame for readability rolling_coefs_df <- as.data.frame(rolling_results) colnames(rolling_coefs_df) <- c("intercept", "v2_beta")
2. Your window parameters are misconfigured
- Double-check that
width = 10(notnrow(mydatareturns)or another large number that covers your full dataset). - The
align = "right"argument ensures each result is tied to the last day of the 10-day window (so you get a daily coefficient for every day after the first 9 days).
3. You're not extracting coefficients correctly
If your custom function returns the full lm object instead of just the coefficients, downstream processing might accidentally grab only the final model's results. Always explicitly return coef(model) or summary(model)$coefficients[,1] in your rolling function.
4. Bonus: Faster alternative with rollRegres
For larger datasets, rollRegres is more efficient than rollapply:
library(rollRegres) # Ensure data is sorted by date mydatareturns <- mydatareturns[order(mydatareturns$date), ] # Run rolling regression rolling_model <- roll_regres(v1 ~ v2, data = mydatareturns, width = 10) # Extract coefficients rolling_coefs <- rolling_model$coef
- Is your dataset sorted chronologically by date?
- Are you using a rolling calculation function (not plain
lm())? - Does your custom function explicitly return the coefficients you need?
- Is the
widthparameter set to 10, not the full number of rows?
内容的提问来源于stack exchange,提问作者user9410653

