[Numpy-discussion] Is there a function to calculate ecnomic beta coefficient in numpy given two time series data.

Keith Goodman kwgoodman at gmail.com
Sun Jun 8 10:57:27 EDT 2008


On Sun, Jun 8, 2008 at 7:02 AM, Vineet Jain (gmail) <vinjvinj at gmail.com> 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)
>> beta
   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)
>> mrkt.shape
   (250, 1)
>> stocks = np.asmatrix(stocks)
>> stocks.shape
   (250, 4)
>> beta, resids, rank, s = np.linalg.lstsq(mrkt, stocks)
>> beta
   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 mailing list