scipy.signal.find_peaks()
由于需要监测波形的峰值,因此找到该函数
该函数通过与周围位置的比较找到峰值
输入:
x: 带有峰值的信号序列
height: 低于指定height的信号都不考虑
threshold: 其与相邻样本的垂直距离
distance: 相邻峰之间的最小水平距离, 先移除较小的峰,直到所有剩余峰的条件都满足为止。
prominence: 个人理解是突起程度,详见peak_prominences
width: 波峰的宽度,详见peak_widths
plateau_size: 保证峰对应的平顶数目大于给定值
----
输出:
peaks: x对应的峰值的索引
python tushare 读取股票数据并存盘
以股票 000063 中兴通讯为例
运行 python stock1.py 000063
find_peaks.py
# coding=utf-8
import os, sys
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import signal
# python 求极值点(波峰波谷)
if len(sys.argv) ==2:
fcode = sys.argv[1]
else:
print('usage: python find_peaks.py fcode ')
sys.exit(1)
if len(fcode) !=6:
print(' fcode is char(6)')
sys.exit(2)
file1 = "./" +fcode +'.csv'
if not os.path.exists(file1):
print(file1 +' is not exists.')
sys.exit(3)
# 用pandas读取csv
df = pd.read_csv(file1)
df = df[['date','close']]
df.index = pd.to_datetime(df.date)
df = df[ df.index.year ==2020 ]
week_max = df[['close']].groupby(df.index.week).max()
#print('week_max:',week_max)
wek_max = week_max['close'].values
print(type(wek_max))
# 求峰值 distance: 极大值点的距离 >=4个水平单位
num_peaks = signal.find_peaks(wek_max, distance=4)
#num_peaks = signal.argrelextrema(wek_max, np.greater)
print(num_peaks)
for i in range(len(num_peaks[0])):
j = num_peaks[0][i]
print(j, week_max.iloc[j,:])
# 求极小值
week_min = df.groupby(df.index.week).min()
#print('week_min:',week_min)
wek_min = week_min['close'].values
num_less = signal.argrelextrema(wek_min, np.less)
print(num_less)
for i in range(len(num_less[0])):
j = num_less[0][i]
#print(j, week_min.iloc[j,:])
# 求最小值
c_min = df['close'].min()
print('c_min:', df.loc[ df['close']==c_min])
# 求最大值
c_max = df['close'].max()
print('c_max:', df.loc[ df['close']==c_max])
运行 python find_peaks.py 000063