Calculating Beta over Rolling Periods
 Calculating Beta over Rolling Periods illmattic Silly Frenchman Posts: 34 Threads: 15 Joined: Jul 2020 Reputation: 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: 34 Threads: 15 Joined: Jul 2020 Reputation: 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: 11,487 Threads: 437 Joined: Sep 2016 Reputation: Sep-27-2020, 11:27 PM Thanks for sharing solution Reply

 Possibly Related Threads… Thread Author Replies Views Last Post Rolling window and apply code JunkBoy 6 770 Jul-23-2022, 07:00 PM Last Post: JunkBoy Hurst Exponent in Rolling Basis illmattic 1 2,676 Jan-06-2021, 09:49 PM Last Post: illmattic Apply rolling window function over time dimension of 3D data Staph 0 1,590 Jan-01-2020, 08:31 AM Last Post: Staph Grouping data based on rolling conditions kapilan15 0 1,485 Jun-05-2019, 01:07 PM Last Post: kapilan15 Pandas .rolling() with some calculations inside irmscher 5 4,805 Apr-04-2019, 11:55 AM Last Post: scidam How to use pandas.rolling mean for 3D input array? Prv_Yadv 1 3,084 Mar-26-2019, 11:49 AM Last Post: scidam Beta Inverse Function ankur2207 5 6,371 Jul-23-2018, 10:07 PM Last Post: ichabod801 Numpy Rolling mean window Thunberd 1 4,218 Jun-14-2018, 01:37 AM Last Post: Larz60+ Creating a matrix of rolling variances vvvcvvcv 1 2,156 May-26-2018, 12:51 PM Last Post: killerrex Rolling sum for a window of 2 days (Pandas) klllmmm 1 9,550 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