使用 SciPy 识别波峰和波谷

scipy.signal 模块中的 find_peaks 函数检测数据中的局部最大值(峰值)。在股价的背景下,这些峰值可以作为潜在的阻力位。让我们来看看我们使用的关键参数:
• distance:指定连续峰值之间的最小数据点数。这有助于避免检测到太多峰,彼此之间太近。
• prominence:峰的突出程度表示它从周围数据中脱颖而出的程度。突出度越高,峰值越显著。|
在我的方法中,我分别处理 “强” 和 “弱” 峰。我将“强”峰值定义为那些具有高突出度和更大间隔(距离)的峰值,以及 52 周高点等重要价格水平。以下是我们使用 find_peaks 找到它们的方法:

# Define the distance between strong peaks (in days).
strong_peak_distance = 60

# Define the prominence (how high the peaks are compared to their surroundings).
strong_peak_prominence = 20 # 这个很重要,不同值会有不同的结果

# Find the strong peaks in the 'high' price data
strong_peaks, _ = sp.signal.find_peaks(
  bars['high'],
  distance=strong_peak_distance,
  prominence=strong_peak_prominence
)

# Extract the corresponding high values of the strong peaks
strong_peaks_values = bars.iloc[strong_peaks]["high"].values.tolist()

# Include the yearly high as an additional strong peak
yearly_high = bars["high"].iloc[-252:].max()
strong_peaks_values.append(yearly_high)

此代码根据价格突出度和分离度确定重要的阻力位。strong_peaks_values 列表包含强峰值的高价,以及 52 周高点

General Peaks
我将一般峰定义为与强峰相比,突出较弱且距离较短的峰。但是,要使价格水平符合“一般峰值”的条件,股票必须多次达到该水平并被拒绝。为了实现这一点,我设置了最小宽度和最小排名阈值。这些阈值有助于将较弱的峰分组到区间中,合并附近彼此过于接近的峰。如果峰值水平达到最低等级(即股票价格在该水平被拒绝的次数足够多),它就会被添加到我的阻力位列表中。
于关注较短时间内较小价格波动的波段交易者特别有用。这些一般峰值与强峰值相辅相成,以提供更全面的股票价格历史阻力位视图。

# Define the shorter distance between general peaks (in days)
# This controls how far apart peaks need to be to be considered separate.
peak_distance = 5

# Define the width (vertical distance) where peaks within this range will be grouped together.
# If the high prices of two peaks are closer than this value, they will be merged into a single resistance level.
peak_rank_width = 2

# Define the threshold for how many times the stock has to reject a level
# Before it becomes a resistance level
resistance_min_pivot_rank = 3

# Find general peaks in the stock's 'high' prices based on the defined distance between them.
# The peaks variable will store the indices of the high points in the 'high' price data.
peaks, _ = sp.signal.find_peaks(bars['high'], distance=peak_distance)

# Initialize a dictionary to track the rank of each peak
peak_to_rank = {peak: 0 for peak in peaks}

# Loop through all general peaks to compare their proximity and rank them
for i, current_peak in enumerate(peaks):
    # Get the current peak's high price
    current_high = bars.iloc[current_peak]["high"]
    
    # Compare the current peak with previous peaks to calculate rank based on proximity
    for previous_peak in peaks[:i]:
        if abs(current_high - bars.iloc[previous_peak]["high"]) <= peak_rank_width:
            # Increase rank if the current peak is close to a previous peak
            peak_to_rank[current_peak] += 1
# Initialize the list of resistance levels with the strong peaks already identified.
resistances = strong_peaks_values

# Now, go through each general peak and add it to the resistance list if its rank meets the minimum threshold.
for peak, rank in peak_to_rank.items():
    # If the peak's rank is greater than or equal to the resistance_min_pivot_rank, 
    # it means this peak level has been rejected enough times to be considered a resistance level.
    if rank >= resistance_min_pivot_rank:
        # Append the peak's high price to the resistances list, adding a small offset (1e-3) 
        # to avoid floating-point precision issues during the comparison.
        resistances.append(bars.iloc[peak]["high"] + 1e-3)

# Sort the list of resistance levels so that they are in ascending order.
resistances.sort()


# Initialize a list to hold bins of resistance levels that are close to each other. resistance_bins = [] # Start the first bin with the first resistance level. current_bin = [resistances[0]] # Loop through the sorted resistance levels. for r in resistances: # If the difference between the current resistance level and the last one in the current bin # is smaller than a certain threshold (defined by peak_rank_w_pct), add it to the current bin. if r – current_bin[-1] < peak_rank_width: current_bin.append(r) else: # If the current resistance level is far enough from the last one, close the current bin # and start a new one. resistance_bins.append(current_bin) current_bin = [r] # Append the last bin. resistance_bins.append(current_bin) # For each bin, calculate the average of the resistances within that bin. # This will produce a clean list of resistance levels where nearby peaks have been merged. resistances = [np.mean(bin) for bin in resistance_bins]

Troughs (Support Levels) 
低谷 (支撑位)
寻找支撑位很酷的一点是,它可以像阻力位一样完成,只是我们传入低点的负值:

troughs, _ = sp.signal.find_peaks(-bars['low'], distance=peak_distance)

其他一切都完全相同,只是使用条形的低值而不是高值。我将把实现留给您,但以下是包含阻力位和支撑位的图表:

Conclusion 
结论

这种区分强峰值和一般峰值的方法提供了一种灵活的方法,可以适应不同的时间框架和股票,使其对交易者和投资者都有价值。无论您是在寻找关键的反转点还是短期交易机会,了解支撑位和阻力位都有助于改进决策并完善您的交易策略。