##### Calculating Beta over Rolling Periods
 Calculating Beta over Rolling Periods illmattic Silly Frenchman Posts: 27 Threads: 11 Joined: Jul 2020 Reputation: 0 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: ```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? Reply illmattic Silly Frenchman Posts: 27 Threads: 11 Joined: Jul 2020 Reputation: 0 Sep-27-2020, 09:45 PM 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``` Reply Larz60+ aetate et sapientia Posts: 9,996 Threads: 372 Joined: Sep 2016 Reputation: 422 Sep-27-2020, 11:27 PM Thanks for sharing solution Reply

 Possibly Related Threads… Thread Author Replies Views Last Post Hurst Exponent in Rolling Basis illmattic 1 134 Jan-06-2021, 09:49 PM Last Post: illmattic Apply rolling window function over time dimension of 3D data Staph 0 630 Jan-01-2020, 08:31 AM Last Post: Staph Grouping data based on rolling conditions kapilan15 0 623 Jun-05-2019, 01:07 PM Last Post: kapilan15 Pandas .rolling() with some calculations inside irmscher 5 2,302 Apr-04-2019, 11:55 AM Last Post: scidam How to use pandas.rolling mean for 3D input array? Prv_Yadv 1 1,315 Mar-26-2019, 11:49 AM Last Post: scidam Beta Inverse Function ankur2207 5 3,877 Jul-23-2018, 10:07 PM Last Post: ichabod801 Numpy Rolling mean window Thunberd 1 2,631 Jun-14-2018, 01:37 AM Last Post: Larz60+ Creating a matrix of rolling variances vvvcvvcv 1 1,088 May-26-2018, 12:51 PM Last Post: killerrex Rolling sum for a window of 2 days (Pandas) klllmmm 1 7,625 Feb-02-2018, 03:24 PM Last Post: klllmmm

Forum Jump:

### User Panel Messages

##### Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020