In this article I show how to calculate beta in Pandas.

To calculate beta in pandas, you can use the cov method to compute the covariance of the returns of two assets, and the var method to compute the variance of one of the assets. Beta is defined as the covariance of the returns of an asset and the returns of a benchmark divided by the variance of the returns of the benchmark:

## Beta calculations

import pandas as pd returns = pd.DataFrame({'asset': [0.03, 0.02, -0.03, 0.04, 0.05], 'benchmark': [0.01, 0.02, 0.01, -0.02, 0.03]}) covariance = returns['asset'].cov(returns['benchmark']) variance = returns['benchmark'].var() beta = covariance / variance print(f'Beta equals: {beta}')

You can also calculate beta using the OLS method from the statsmodels library:

import statsmodels.api as sm X = returns['benchmark'] y = returns['asset'] model = sm.OLS(y, X).fit() beta = model.params[0] print(f'Beta equals: {beta}')

See also:

How to calculate variance in Pandas

How to calculate standard deviation in Pandas

How to calculate the IQR in Pandas

How to calculate z score