Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

pandas - Find maxima and minima within data and append True/False to corresponding row - Python

I want to find swing high and swing lows in stock market data. I want to be able to append each point to a column. Ex.) Have a column for isHigh and isLow that lines up with the Close price column. So each day that goes on, if the price is not a swing high or low, it will return False in the isHigh/isLow column. If it is a swing high or low, it will return True.

I have been able to find maxima/minma or turning points in stock market data, but all it returns is the number of turning points or the number of each point.

I'm having trouble extracting the actual points in reference to price.

I've used numpy and scipy argrelextrema.

```  
import matplotlib
from scipy import signal
import numpy as np
import matplotlib.pyplot as plt
 
#Generate random data.
data_x = df['close']
data_y = df['close']
 
#Find peaks(max).
peak_indexes = signal.argrelextrema(data_y.to_numpy(), np.greater)
peak_indexes = peak_indexes[0]
 
#Find valleys(min).
valley_indexes = signal.argrelextrema(data_y.to_numpy(), np.less)
valley_indexes = valley_indexes[0]

**peak_indexes and valley_indexes only returns a numbered list of the points in numerical order.**
---

and I've tried.

close = df['Adj Close']

def turningpoints(close):
    dx = np.diff(close)
    return np.sum(dx[1:] * dx[:-1] < 0)```

This returns a number 646, which is the amount of peaks and valleys in total

Any help is appreciated, thanks

question from:https://stackoverflow.com/questions/65892304/find-maxima-and-minima-within-data-and-append-true-false-to-corresponding-row

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Take advantage of the fact that rolling with window=len(df) and min_periods=1 gives you an easy window up to the current point. Then just check if value is the min() or max() up to that point.

df["isHigh"] = ( df["close"].rolling(len(df),1).max() == df["close"] )
df["isLow"]  = ( df["close"].rolling(len(df),1).min() == df["close"] )

Example:

   close  isHigh  isLow
0      0    True   True
1     11    True  False
2      2   False  False
3     22    True  False
4    -55   False   True
5     44    True  False
6     43   False  False
7     44    True  False

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...