注:最近写指标,采用pandas重新编写了macd指标的算法,主要是调用ewm这个指数平滑的函数,效率大大提高。
def cal_macd_system(data,short_,long_,m): ''' data是包含高开低收成交量的标准dataframe short_,long_,m分别是macd的三个参数 返回值是包含原始数据和diff,dea,macd三个列的dataframe ''' data['diff']=data['close'].ewm(adjust=False,alpha=2/(short_+1),ignore_na=True).mean()-\ data['close'].ewm(adjust=False,alpha=2/(long_+1),ignore_na=True).mean() data['dea']=data['diff'].ewm(adjust=False,alpha=2/(m+1),ignore_na=True).mean() data['macd']=2*(data['diff']-data['dea']) return data
两种算法的结果不变,但是第一种的效率大大大的提高。
以后指标系列文章所用的示范数据都是来源于网易财经-000001上证指数,2010年到2017年5月数据
###经热心朋友casinozyz指正,该macd算法修改为如下,稍后会做一个更有效率的版本.(以前吹得牛逼2019-01-04已经实现)
import pandas as pd import numpy as np import datetime import time #获取数据 df=pd.read_csv('C:/Users/HXWD/Desktop/000001.csv',encoding='gbk') df.columns=['date','code','name','close','high','low','open','preclose', 'change','change_per','volume','amt'] df=df[['date','open','high','low','close','volume','amt']] df.head() def get_EMA(df,N): for i in range(len(df)): if i==0: df.ix[i,'ema']=df.ix[i,'close'] if i>0: df.ix[i,'ema']=(2*df.ix[i,'close']+(N-1)*df.ix[i-1,'ema'])/(N+1) ema=list(df['ema']) return ema def get_MACD(df,short=12,long=26,M=9): a=get_EMA(df,short) b=get_EMA(df,long) df['diff']=pd.Series(a)-pd.Series(b) #print(df['diff']) for i in range(len(df)): if i==0: df.ix[i,'dea']=df.ix[i,'diff'] if i>0: df.ix[i,'dea']=(2*df.ix[i,'diff']+(M-1)*df.ix[i-1,'dea'])/(M+1) df['macd']=2*(df['diff']-df['dea']) return df get_MACD(df,12,26,9) df