Calculating Beta over Rolling Periods - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: Calculating Beta over Rolling Periods (/thread-29966.html) |
Calculating Beta over Rolling Periods - illmattic - Sep-27-2020 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_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? RE: Calculating Beta over Rolling Periods - illmattic - Sep-27-2020 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 RE: Calculating Beta over Rolling Periods - Larz60+ - Sep-27-2020 Thanks for sharing solution |