简体   繁体   中英

How to eliminate loops using numpy array to vectorize a function

I have an array of a stock's price like below. My basic idea is to be able to find the first instance where the price is up by at least 10% and then down by 5% from the first instance where it was up by 10% and on, recursively until the end of array.

price_array=np.array([ 4261.48,  4261.48,  4280.56, ..., 45264.9 , 45240.  , 45215.06])

What i want to do is to create a new array(b) by reading the price_array from left to right where;

b[0] = price_array[0]

b[1] = first value in price_array which is >= 1.1*b[0]

b[2] = first value in price_array after the value of b[1] which is <= 0.95*b[1]

b[3] = first value in price_array after the value of b[2] which is >= 1.1*b[2]

b[4] = first value in price_array after the value of b[3] which is <= 0.95*b[3]

.....................................

.....................................

.....................................

.....................................

.....................................

b[n] = first value in price_array after the value of b[n-1] which is.....

How can we do that using numpy in order to eliminate loops, iterations?

You can divide the array from the first element forward by the array until the last element-1 like this:

price_array[1:]/price_array[:-1]

You'll get an array as a result that represents exactly what you wanted.

result[0] = price_array[1]/price_array[0] 
.
.
.
result[n-2] = price_array[n-1]/price_array[n-2] 

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