I am trying to calculate Slope for the rolling window of 5 and 20 periods and append it to the existing data frame. The length of the total dataset would be let's say 30 days. I have two columns "Volume" and "Vpt", I have tried sklearn (linregress) and numpy (polyfit) but in both the scenario, I am getting an error message "IndexError: iloc cannot enlarge its target object". Please see below code and help to resolve this issue.

for j in range(len(temp)):
   x = np.array(temp['Volume'][j:j+5])
   y = np.array(temp['vpt'][j:j+5])
   slope = np.polyfit(x,y,1)
   # slope, intercept, r_value, p_value, std_err = linregress(x, y)
   temp['slope_5'].iloc[j+5] = slope[0]
   a = np.array(temp['Volume'][j:j+20])
   b = np.array(temp['vpt'][j:j+20])
   slope_1 = np.polyfit(a,b,1)
   # slope, intercept, r_value, p_value, std_err = linregress(a, b)
   temp['slope_20'].iloc[j+20] = slope_1[0]

1 Answer 1


Actually, I found an answer to my question above.

def np_slope(data):
    return np.polyfit(data.index.values,data.values,1)[0]
temp.index = temp['Volume']
temp['slope_5'] = temp['vpt'].rolling(5,min_periods=5).apply(np_slope,raw=False)        
temp['slope_20']= temp['vpt'].rolling(20,min_periods=20).apply(np_slope,raw=False)        

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.