I need to compute rolling window regressions in Python where the standard errors are corrected for HAC (Newey-West, 1987). I know that statsmodels has a function for rolling window regressions (Rolling Regression), but the standard errors cannot be corrected for HAC in this function. Therefore I have defined my own function.
I have a panel data set with 108,768 rows (410 unique funds) and the structure looks as follows:
funds = pd.DataFrame({
"Fund": ["A", "A", "A", "A", "B", "B", "B", "B"],
"Excess_Return": [np.NaN, 0.172, 0.0465, 0.039, 0.003995, -0.022139, 0.009518, 0.03233],
"Regression_Constant": [1,1,1,1,1,1,1,1],
"RMRF": [0.0118,0.0557,0.0129,0.0403,0.0118,0.0557,0.0129,0.0403],
"SMB": [0.0445,0.1838,-0.1539,-0.0496,0.0445,0.1838,-0.1539,-0.0496],
"HML": [-0.0189,-0.0981,0.0823,0.0725,-0.0189,-0.0981,0.0823,0.0725],
"RMW": [-0.0629,-0.1876,0.1182,0.0767,-0.0629,-0.1876,0.1182,0.0767],
"CMA": [0.0474,-0.0035,-0.0161,0.0562,0.0474,-0.0035,-0.0161,0.0562]})
The function is defined as follows:
min_t = 30
t = 36
def process(x):
if x["Excess_Return"].count() >= min_t:
reg = smf.ols("Excess_Return ~ RMRF + SMB + HML + RMW + CMA", data = x).fit(cov_type="HAC", cov_kwds={"maxlags":1})
return [
reg.params[0],
reg.params["RMRF"],
reg.params["SMB"],
reg.params["HML"],
reg.params["RMW"],
reg.params["CMA"],
# tvalues
reg.tvalues[0],
reg.tvalues["RMRF"],
reg.tvalues["SMB"],
reg.tvalues["HML"],
reg.tvalues["RMW"],
reg.tvalues["CMA"],
]
# Else return NaN
return [np.nan] * 10
To run the function and get the results in a data frame i run the following command:
df_1 = funds.join(
# join new DataFrame back to original
pd.DataFrame(
(process(x) for x in funds.rolling(t)),
columns=["alpha", "Beta_RMRF", "Beta_SMB", "Beta_HML", "Beta_RMW", "Beta_CMA",
"t_alpha", "t_RMRF", "t_SMB", "t_HML", "t_RMW", "t_CMA"]
)
)
This returns the correct t-stats of the regressions. However, since I have multiple funds, I need to group the funds by their name, i.e. that the returns of fund A are not taken into account when running regressions for fund B. Does anybody have a solution how to rearrange the code?
return
output of the function. (2) if you want to do the rolling regression then I suggest you to visit this link: pandas.pydata.org/docs/reference/api/…