Calculate a rolling regression in Pandas and store the slope

Viewed 5592

I have some time series data and I want to calculate a groupwise rolling regression of the last n days in Pandas and store the slope of that regression in a new column.

I searched the older questions and they either haven't been answered, or used Pandas OLS which I heard is deprecated.

I figured that I probably could use df.rolling.apply() in combination with the scipy.stats.linregress function, but I can't figure out a lambda function that does what I want to do.

Here is some sample code

import numpy as np
import pandas as pd
from scipy.stats import linregress

# make sample data
days = 21
groups = ['A', 'B', 'C']
data_days = list(range(days)) * len(groups)
values = np.random.rand(days*len(groups))

df = pd.DataFrame(data=zip(sorted(groups*days), data_days, values), 
                  columns=['group', 'day', 'value'])

# calculate slope of regression of last 7 days
days_back = 7

grouped_data = df.groupby('group')
for g, data in grouped_data:
    window = data.rolling(window=days_back,
                          min_periods=days_back)

I need a new column called 'slope' in which, from day 7 onward, the slope of a linear regression through the last 7 days is stored.

1 Answers

I had some wrong assumptions, first I don't need to loop through the groups, and second I didn't really understand how rolling.apply worked...

So here is the (seemingly) working code. I used the linregress function from scipy.stats:

import numpy as np
import pandas as pd
from scipy.stats import linregress

# create random sample data
days = 14
groups = ['A', 'B', 'C']
data_days = list(range(days)) * len(groups)
values = np.random.rand(days*len(groups))

df = pd.DataFrame(data=zip(sorted(groups*days), data_days, values), 
                  columns=['group', 'day', 'value'])

def get_slope(array):
    y = np.array(array)
    x = np.arange(len(y))
    slope, intercept, r_value, p_value, std_err = linregress(x,y)
    return slope


# calculate slope of regression of last 7 days
days_back = 3

df['rolling_slope'] = df.groupby('group')['value'].rolling(window=days_back,
                               min_periods=days_back).apply(get_slope, raw=False).reset_index(0, drop=True)

print(df)
Related