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

量化交易吧 /  量化平台 帖子:3365935 新帖:0

量化交易(JoinQuant数据)-MACD/EMA/DIFF/DEA算法-Python代码实现

到此一游发表于:8 月 20 日 16:00回复(1)
import talib
import datetime
import jqdata
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.finance as mpf
'''
默认股票代码格式(000915)转换为聚宽代码格式(000915.XSHG)
author:aaron-clark-aic 18/07/2018
'''
def standardStocks(stocks):
    _stocks = list(get_all_securities('stock').index)
    _standardStocks = []
    for i in stocks:
        _standardStocks =_standardStocks+[code for code in _stocks if code.upper().startswith(i)]
    return _standardStocks
'''
EMA_today=α * Price_today + ( 1 - α ) * EMA_yesterday
α=2/(N+1)
算法需要特别注意边界的转折处,前n的计算和n+1完全不同

author:aaron-clark-aic 23/07/2018
'''
def ema(c_list,n=12):
    y_list=[]
    _n = 1    
    for c in c_list: 
        if c == c_list[0]:
            y = c
        elif _n<n:
            y= c*2/(_n+1) + (1- 2/(_n+1))*y_list[-1] 
        else:
            y=c*2/(n+1)+(1-2/(n+1))*y_list[-1]
        y_list.append(y)
        _n = _n+1        
    return y_list

'''
DIFF线 (Difference)收盘价短期、长期指数平滑移动平均线间的差

author:aaron_clark_aic 23/07/2018
'''
def diff(c_list,short=12,long=26):
    _diff = list(map(lambda x:x[0]-x[1],zip(ema(c_list,short),ema(c_list,long))))
    return _diff

'''
DEA线 (Difference Exponential Average)DIFF线的M日指数平滑移动平均线

author:aaron_clark_aic 23/07/2018
'''
def dea(c_list,m=9):
    return ema(diff(c_list),n=m)

'''
MACD线 DIFF线与DEA线的差,柱状线

author:aaron_clark_aic 23/07/2018
'''
def bar(c_list):
    _bar = list(map(lambda x:2*(x[0]-x[1]),zip(diff(c_list),dea(c_list))))
    return _bar

'''
没有绘制蜡烛图部分,可以叠加绘制
MACD线也即是在使用MACD指标时在图表上看到的MACD柱状线,常用于分析股票的买入、卖出时机。当MACD线(macd柱)位于0坐标上沿,
即由负变正时为买入时机;当MACD线(macd柱)位于0坐标下沿,即由正变负时为卖出时机。DIF黄色,DEA蓝色。

author:aaron_clark_aic 23/07/2018
'''
def macd(security=standardStocks(['000915']),start_date=(datetime.date.today()-datetime.timedelta(days=200)),end_date=datetime.date.today()):
    _data = get_price(security = security,start_date=start_date,end_date=end_date,fields=['close'])
    _close = np.hstack(_data['close'].values)
    _diff = diff(_close)
    _dea = dea(_close)
    _bar = bar(_close)
    plt.plot(range(len(_diff)),_diff,"y",lw=0.5)
    plt.plot(range(len(_dea)),_dea,"b",lw=0.5)
    plt.bar(range(len(_bar)),_bar,0.1)
    plt.show()
macd()

全部回复

0/140

量化课程

    移动端课程