I'm trying to calculate various beta for a CAPM model from past recorded monthly stock prices and market prices.
Date S_adjclose M_adjclose S_returns M_returns
1 2006-03-01 83.057541 1294.869995 0.031026 0.011035
2 2006-04-01 88.786636 1310.609985 0.066703 0.012082
3 2006-05-01 83.362877 1270.089966 -0.063033 -0.031405
4 2006-06-01 81.792465 1270.199951 -0.019018 0.000087
5 2006-07-01 86.534538 1276.660034 0.056358 0.005073
.. ... ... ... ... ...
168 2020-02-01 8.720000 2954.219971 -0.048135 -0.087860
169 2020-03-01 6.420000 2584.590088 -0.306201 -0.133668
170 2020-04-01 7.410000 2912.429932 0.143412 0.119421
171 2020-05-01 8.400000 3044.310059 0.125401 0.044287
172 2020-06-01 9.460000 3053.239990 0.118841 0.002929
the Date column data type is already datetime64.
so far I managed to calculate the beta for the entire dataset using
#cov matrix
covmat = np.cov(data["S_returns"], data["M_returns"])
#get beta
beta = covmat[0, 1] / covmat[1, 1]
Now I want to create a new data frame with the beta recorded for every five years, in monthly intervals. For example from March 2006 till March 2011, than from April 2006 till April 2011, so on and so forth until June 2020.
Is there a way I can loop this somehow using the timestamps?
Thanks,
Patrick