Skip to main content
 首页 » 编程设计

python之python 中只有左基的峰日珥的累积和

2024年11月24日13exmyth

我试图在 python 中找到价格序列的 峰值日珥的累积总和。换句话说,它是回撤或恢复的总和。

首先我尝试了以下:

from scipy.signal import find_peaks, peak_prominences 
import matplotlib.pyplot as plt 
 
x = np.linspace(0, 6 * np.pi, 1000) 
x = np.sin(x) + 0.6 * np.sin(2.6 * x) 
 
peaks, _ = find_peaks(x) 
prominences = peak_prominences(x, peaks)[0] 
prominences 
 
contour_heights = x[peaks] - prominences 
plt.plot(x) 
plt.plot(peaks, x[peaks], "x") 
plt.vlines(x=peaks, ymin=contour_heights, ymax=x[peaks]) 
plt.show() 

结果和情节是一个很好的起点。但存在以下问题:

  • 峰值与左右最低值进行比较。我只需要与左低值进行比较。
  • 峰值只应与前一个谷值/低值进行比较,而不是谷值中的最低值
  • 如果将峰值与之前的波谷/波谷中的最低值进行比较,则应忽略中间突出部分。

what i got from the code as a starting point

my required result

一旦视觉确认,我需要计算所有峰日珥的总和(峰谷之间的距离)。请帮忙。

请您参考如下方法:

假设我没有误解您的要求(如果是请告诉)这可能会解决您的问题:

您可以使用 peak_prominences 返回的 left_bases 计算“左突出度” :

from scipy.signal import find_peaks, peak_prominences 
import matplotlib.pyplot as plt 
 
x = np.linspace(0, 6 * np.pi, 1000) 
x = np.sin(x) + 0.6 * np.sin(2.6 * x) 
 
peaks, _ = find_peaks(x) 
_, left_bases, _ = peak_prominences(x, peaks) 
left_prominences = x[peaks] - x[left_bases] 

这应该可以解决您的第一个问题。如果我理解正确的话,您想忽略较大峰左基之后的峰:

keep = ~( 
    (left_prominences[:-1] < left_prominences[1:])  
    & (peaks[:-1] > left_bases[1:]) 
) 
keep = np.concatenate((keep, [True]))  # last peak is always kept 
peaks = peaks[keep] 
left_prominences = left_prominences[keep] 
 
plt.plot(x) 
plt.vlines(x=peaks, ymin=x[peaks]-left_prominences, ymax=x[peaks]) 

最后总和很容易计算:

np.sum(left_prominences)  # returns 8.740800984535955 

这种方法应该是合理的快速。