Stock Beta Calculator with Python

Stock Beta Calculator with Python

To calculate the Beta for a stock, we can use simple linear regression. With python, we’ll make use of the pandas and statsmodel package. We first need to stuff data from a mysql database into a pandas dataframe. The data will be from a five year period broken down monthly. This code will do that,

def beta(symbol, start_date, end_date):
    connection = MySQLdb.connect("localhost","myuser","mypass","dbname" )
    symbols = "%s,%s" % (symbol,"SPY")
    sql = "call get_stocks('{0}','{1}','{2}')".format(symbols, start_date, end_date)
    df = psql.frame_query(sql, con=connection,index_col='trade_date')
    df = df.resample("M", how='mean')
    Stocks = df.join(np.log(df).diff(), rsuffix='_diff' )
    symbol_diff = "%s%s" % (symbol,"_diff")
    Stocks['Intercept'] = np.ones(( len(Stocks), ))
    Stocks[symbol] = Stocks[symbol_diff]
    Stocks['SP500'] = Stocks['SPY_diff']
    Y = Stocks[symbol][:-1]
    X = Stocks[['SP500','Intercept']][:-1]
    result = sm.OLS( Y, X ).fit()
    return result.summary()

The code above uses a mysql stored procedure called “get_stocks” to get the two columns of stock data. The data is compared against SPY, which is the S&P500. The results using IBM from May 2009 to May 2014 are then put in a summary table:

                            OLS Regression Results                            
==============================================================================
Dep. Variable:                    IBM   R-squared:                       0.354
Model:                            OLS   Adj. R-squared:                  0.343
Method:                 Least Squares   F-statistic:                     31.81
Date:                Tue, 06 May 2014   Prob (F-statistic):           5.30e-07
Time:                        15:17:51   Log-Likelihood:                 299.51
No. Observations:                  60   AIC:                            -595.0
Df Residuals:                      58   BIC:                            -590.8
Df Model:                           1                                         
==============================================================================
                 coef    std err          t      P>|t|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
SP500          0.6592      0.117      5.640      0.000         0.425     0.893
Intercept      0.0002      0.000      0.845      0.401        -0.000     0.001
==============================================================================
Omnibus:                        0.960   Durbin-Watson:                   2.521
Prob(Omnibus):                  0.619   Jarque-Bera (JB):                0.543
Skew:                           0.225   Prob(JB):                        0.762
Kurtosis:                       3.121   Cond. No.                         541.

To get the Beta for IBM, we use the coefficient for SP500, which in this case is 0.6592.

Leave a Reply

Your email address will not be published. Required fields are marked *

twenty − nineteen =