请 [注册] 或 [登录]  | 返回主站

量化交易吧 /  数理科学 帖子:3365778 新帖:10

MACD warn

螺罗丝发表于:8 月 20 日 16:00回复(1)

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))
<matplotlib.axes._subplots.AxesSubplot at 0x7f0e21a1f5d0>

全部回复

0/140

量化课程

    移动端课程