MACD 源码定义

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 talib

df=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 ewma

ps=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-DEA

def mplot(DIF,DEA,MACD,CUT=300):
#    CUT=300
    plt.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)

MACD 源码定义_第1张图片

posted on 2018-11-12 17:01 luoganttcc 阅读(...) 评论(...) 编辑 收藏

你可能感兴趣的:(MACD 源码定义)