I want to calculate betas and intercept regressing returns on index factor for every date in the dataset, grouping by company, and using the interval [-50,-10] prior to that date. I would also like to save the intercept and the beta in two new columns in the data frame.
   Company      Return       date indexfactor
1:    TSLA          NA 2020-01-02           1
2:    TSLA  0.02963319 2020-01-03           2
3:    TSLA  0.01925467 2020-01-06           3
4:    TSLA  0.03880052 2020-01-07           1
5:    TSLA  0.04920485 2020-01-08           2
6:    TSLA -0.02194501 2020-01-09           3
eg. the intercept and beta for TSLA on 01.01.2021, I would like to regress the returns on the index factor in the interval -50 and -10 observations back in time and store as the beta and intercept for 01.01.2021.
I have tried this code:
stocks[,as.list(coef(lm(Returns ~ indexfactor))), by=Company] but it does not take into account the relevant interval for calculations.
I would be very greatful if someone could help me!
require(quantmod)
require(zoo)
require(data.table)
# STOCK DATA.FRAME
TSLA <- as.data.frame(getSymbols.yahoo("TSLA", from="2020-01-01", verbose=F, auto.assign=F))
AAPL <- as.data.frame(getSymbols.yahoo("AAPL", from="2020-01-01", verbose=F, auto.assign=F))
MSFT <- as.data.frame(getSymbols.yahoo("MSFT", from="2020-01-01", verbose=F, auto.assign=F))
TSLA$Company <- c("TSLA")
AAPL$Company <- c("AAPL")
MSFT$Company <- c("MSFT")
TSLA$Return <- Delt(TSLA$TSLA.Adjusted)
AAPL$Return <- Delt(AAPL$AAPL.Adjusted)
MSFT$Return <- Delt(MSFT$MSFT.Adjusted)
colnames(TSLA) <- c("Open", "High", "Low", "Close", "Volume", "Adjusted", "Company","Return")
colnames(AAPL) <- c("Open", "High", "Low", "Close", "Volume", "Adjusted", "Company","Return")
colnames(MSFT) <- c("Open", "High", "Low", "Close", "Volume", "Adjusted", "Company", "Return")
stocks <- rbind(TSLA, AAPL, MSFT)
rm(AAPL,MSFT,TSLA)
stocks$date <- as.Date(rownames(stocks), format = "%Y-%m-%d")
stocks$Open <- NULL
stocks$Close <- NULL
stocks$High <- NULL
stocks$Low <- NULL
stocks$Volume <- NULL
stocks$Adjusted <- NULL
stocks$indexfactor <- 1:length(stocks)
stocks <- data.table(stocks)
 
    