Financial Calculations & Valuation Intermediate

Calculate Rolling 60-Day Stock Beta & Jensen's Alpha vs Nifty 50 / S&P 500 in Python

Compute rolling Covariance Beta, annualized Jensen's Alpha, and R-squared correlation of any stock against Nifty 50 or S&P 500 in Python Pandas.

#pandas#numpy

Problem Statement

A stock's Beta is not static—it expands during high-momentum earnings phases and contracts during consolidation. Computing rolling 60-day Beta and Jensen's Alpha helps hedge portfolios accurately with index futures.

Formula / Core Logic

Rolling_Beta = Rolling_Cov(Stock_Ret, Index_Ret, 60) / Rolling_Var(Index_Ret, 60) Jensens_Alpha = Stock_Annual_Ret - [Rf + Beta * (Index_Annual_Ret - Rf)]

Installation

pip install pandas numpy
rolling-beta-alpha-benchmark-regression-nifty-python.py
import pandas as pd
import numpy as np

def calculate_rolling_beta_alpha(stock_close, index_close, window=60, rf_annual=0.065):
    s_ret = stock_close.pct_change()
    m_ret = index_close.pct_change()
    
    rolling_cov = s_ret.rolling(window).cov(m_ret)
    rolling_var = m_ret.rolling(window).var()
    beta = rolling_cov / rolling_var
    
    rf_daily = rf_annual / 252.0
    alpha_daily = (s_ret.rolling(window).mean() - rf_daily) - beta * (m_ret.rolling(window).mean() - rf_daily)
    alpha_annual_pct = alpha_daily * 252.0 * 100.0
    
    return pd.DataFrame({'Rolling_Beta': beta.round(3), 'Annualized_Alpha_Pct': alpha_annual_pct.round(2)})

Get the Complete 100+ Python Quant & Automation Bundle

Instant lifetime access to all production-ready scripts, valuation models, and trading bots ($19).

Buy Full Bundle on Gumroad ($19) →

Frequently Asked Questions

Q: How do I beta-neutralize a ₹10 Lakh stock portfolio with a portfolio Beta of 1.35?

Short ₹13.50 Lakh (`10L x 1.35`) worth of Nifty Futures to make the net portfolio delta/beta neutral against market crashes.