[Numpy-discussion] Is there a function to calculate ecnomic beta coefficient in numpy given two time series data.
Sun Jun 8 09:57:27 CDT 2008
On Sun, Jun 8, 2008 at 7:02 AM, Vineet Jain (gmail) <firstname.lastname@example.org> wrote:
> Currently my code handles market returns and stocks as 1d arrays. While the
> function below expects a matrix. Is there an equivalent of the function
> below which works with numpy arrays?
> I'd like to do:
> beta, resids, rank, s = mp.linalg.lstsq(mrkt_1d_array, stock_1d_array)
lstsq works with arrays if the dimensions are right. Here's one way to do it:
>> import numpy as np
>> mrkt = np.random.randn(250,1) # <----- 250 days of returns
>> stocks = np.random.randn(250, 4) # <---- 4 stocks
>> beta, resids, rank, s = np.linalg.lstsq(np.atleast_2d(mrkt), stocks)
array([[-0.02000282, 0.11898366, 0.01010665, -0.03257696]])
Let's make sure the results are the same as the matrix case:
>> mrkt = np.asmatrix(mrkt)
>> stocks = np.asmatrix(stocks)
>> beta, resids, rank, s = np.linalg.lstsq(mrkt, stocks)
matrix([[-0.02000282, 0.11898366, 0.01010665, -0.03257696]]) #
<--- Yep, they are the same
There is also np.clip if you want to clip returns. And np.linalg.eigh
if you want to estimate the betas from an estimate of the covariance
matrix, where you throw out the eigenvectors with small eigenvalues.
More information about the Numpy-discussion