简体   繁体   中英

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? The docs dont 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)

Would 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 the would the 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.]

The slope and slope2 are what Im after except the -6, -6.5 and -14 arent the results I am looking for.

this 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

I'm assuming you mean the slope calculated on every 3rd and 5th element so that you have a series of (exact, not least-squares) slopes?

If so, you'd just do something along the lines of:

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

I'm probably entirely misunderstanding what you mean, though. I've never head the term "3 period slope" before...

If you want more of a "moving window" calculation (so that you have the same number of input elements as output elements), just model it as a convolution with a window of [-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')

Just use the subset of the data that contains the points (periods -- I'm assuming you're talking about financial data here) you're interested in:

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 isn't the most efficient approach, btw, if all you want is the slopes, but it's easy.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM