MACD 源码定义
要理解MACD ,首先要理解指數衰減加權平均,下文有EMA源碼
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 12 16:36:02 2018@author: lg """import tushare as ts import pandas as pd import matplotlib.pyplot as plt import numpy as np import talibdf=ts.get_k_data('600600') def EMA(ps,period=5,exp=0.1):ewma=pd.Series(0.0,index=ps.index)ewma[period-1]=ps[:period].mean()for i in range(period,len(ps)):ewma[i] =exp*ps[i]+(1-exp)*ewma[i-1]return ewmaps=df.close ema=EMA(ps) DIF=EMA(ps,12,2/(12+1))-EMA(ps,26,2/(26+1)) DEA=EMA(DIF,9,2/(9+1)) MACD=DIF-DEAdef mplot(DIF,DEA,MACD,CUT=300): # CUT=300plt.subplot(211)plt.plot(DIF[CUT:],\label="DIF",color='k')plt.plot(DEA[CUT:], label="DEA",\color='b',linestyle='dashed')plt.title("信號線DIF與DEA")plt.legend()plt.subplot(212)plt.bar(left=MACD[CUT:].index,\height=MACD[CUT:],\label='MACD',color='r')plt.legend()mplot(DIF,DEA,MACD,CUT=500)用talib 實現結果是一樣的
dif, dea, macd = talib.MACD(df['close'].values, fastperiod=12, slowperiod=26, signalperiod=9) dif=pd.Series(dif) dea=pd.Series(dea) macd=pd.Series(macd) mplot(dif,dea,macd,CUT=500)總結