Sep-27-2020, 04:36 PM
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:
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_betaThe 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?
