MACD 调参
import datetime,talib,numpy as np
now=datetime.datetime.now()
now=now.replace(hour=9,minute=0,second=0,microsecond=0)
start = now + datetime.timedelta(-880)
#1 获取获取数据
df=get_price('000001.XSHG', start_date=start, end_date=now, frequency='daily', fields='close', skip_paused=False, fq='pre', count=None)
#2 设置MACD 参数 fastperiod=12,slowperiod=26,signalperiod=9
df['diff'],df['dea'],df['macdhist']=talib.MACD(df['close'].values,fastperiod=12,slowperiod=26,signalperiod=9)
df = df.fillna(0)
df['dea_direction'] = np.where(df['dea'] > 0, 1, -1)
g = {'max_close':0,'last_max_close':0,'last_max_dea':0,'max_dea':0,'direction':0,'warn':0}
#3 计算逻辑
def calc_max(row):
if g['direction'] == 0:
g['direction'] = row['dea_direction']
change = False
if g['direction'] != row['dea_direction']:
g['direction'] = row['dea_direction']
change = True
if g['direction'] == 1:
if change:
g['last_max_close'] = g['max_close']
g['max_close'] = row['close']
g['last_max_dea'] = g['max_dea']
g['max_dea'] = row['dea']
g['max_close'] = max(g['max_close'] ,row['close'])
g['max_dea'] = max(g['max_dea'], row['dea'])
if g['max_close'] > g['last_max_close'] and g['max_dea'] < g['last_max_dea'] and g['last_max_dea'] > 0:
g['warn'] = 2000
else :
g['warn'] = 0
return g['max_close'],g['last_max_close'],g['max_dea'],g['last_max_dea'],g['warn']
ret = df.apply(calc_max, axis=1)
df['max_close']=ret.map(lambda values:values[0])
df['last_max_close']=ret.map(lambda values:values[1])
df['max_dea']=ret.map(lambda values:values[2])
df['last_max_dea']=ret.map(lambda values:values[3])
df['warn']=ret.map(lambda values:values[4])
#保存到CSV
df.to_csv('MACD_warn.csv')
df.plot(figsize=(14,12))