'''
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()