Python Forum

Full Version: Calculating Beta over Rolling Periods
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I'm trying to create a function that calculates the x-day beta of a stock to the overall market. This is my current function:

def beta(individual, market, period): 
    returns = individual.join(market).dropna()
    returns = returns.pct_change().dropna()
    cov = returns.tail(period).cov()
    cov_with_market = cov.iloc[0,1]
    market_var = returns.iloc[0:,1].tail(period).var()
    individual_beta = cov_with_market / market_var
    return individual_beta
The problem with this is that it gives me just one beta for the last 30 days on the dataframe. How would I have it be a rolling beta so that it returns a dataframe calculating the beta from the previous 30 days, not the last 30?
Figured it out....

def beta(individual, market, period): 
    returns = individual.join(market).dropna()
    returns = returns.pct_change().dropna()
    cov = returns.iloc[0:,0].rolling(period).cov(returns.iloc[0:,1])
    market_var = returns.iloc[0:,1].rolling(period).var()
    individual_beta = cov / market_var
    return individual_beta
Thanks for sharing solution