How to calculate slope in numpy

If I have an array of 50 elements, how would I calculate a 3-period slope and a 5-period slope? Documents do not add much ...

>>> from scipy import stats >>> import numpy as np >>> x = np.random.random(10) >>> y = np.random.random(10) >>> slope, intercept, r_value, p_value, std_err = stats.linregress(x,y) 

Will this work?

 def slope(x, n): if i<len(x)-n: slope = stats.linregress(x[i:i+n],y[i:i+n])[0] return slope 

but will arrays be the same length

@joe:

 xx = [2.0 ,4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30] x = np.asarray(xx, np.float) s = np.diff(x[::3])/3 window = [1, 0, 0, 0, -1] window2 = [1, 0, -1] slope = np.convolve(x, window, mode='same') / (len(window) - 1) slope2 = np.convolve(x, window2, mode='same') / (len(window2) - 1) print x print s print slope print slope2 

Results.....

 [ 2. 4. 6. 8. 10. 12. 14. 16. 18. 20. 22. 24. 26. 28. 30.] [ 2. 2. 2. 2.] [ 1.5 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. -6. -6.5] [ 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. -14.] 

Tilt and tilt2 are what Im after exceptions -6, -6.5 and -14 arent the results I'm looking for.

it worked .......

 window = [1, 0, 0, -1] slope = np.convolve(xx, window, mode='valid') / float(len(window) - 1) padlength = len(window) -1 slope = np.hstack([np.ones(padlength), slope]) print slope 
+6
source share
2 answers

I suppose you mean the slope calculated for every third and fifth elements, so that you have a series of (exact, not least squares) slopes?

If so, you are simply doing something like:

 third_period_slope = np.diff(y[::3]) / np.diff(x[::3]) fifth_period_slope = np.diff(y[::5]) / np.diff(x[::5]) 

Perhaps I, probably, do not understand at all what you mean. I never head the term "3 period tilt" until ...

If you want more calculation of the "moving window" (so that you have the same number of input elements as the output elements), just simulate it as a convolution with the window [-1, 0, 1] or [-1, 0, 0, 0, 1] .

eg.

 window = [-1, 0, 1] slope = np.convolve(y, window, mode='same') / np.convolve(x, window, mode='same') 
+7
source

Just use a subset of the data containing points (periods - I assume that you are talking about financial data here) that interest you:

 for i in range(len(x)): if i<len(x)-3: slope, intercept, r_value, p_value, std_err = stats.linregress(x[i:i+3],y[i:i+3]) if i<len(x)-5: slope, intercept, r_value, p_value, std_err = stats.linregress(x[i:i+5],y[i:i+5]) 

(This is not the most efficient approach, by the way, if all you need is slopes, but it's easy.)

+3
source

Source: https://habr.com/ru/post/896893/


All Articles