最近正在研究算法交易,看了几本英文原版书。本文总结自Packt出版社的《Learn Algorithmic Trading - Fundamentals of Algorithmic Trading》(图1)。现将该书的MACD技术指标部分进行总结,并对数据处理等函数作了相应改动,供有须要的读者学习研究。
html
MACD(Moving average convergence divergence)平滑异同移动平均线,1979年由美国人杰拉德·阿佩尔(Gerald Appel)及福雷德·海期尔(Fred Hitschler)所发明,在股票、期货等的市场分析等方面都有着普遍的应用。python
Python绘图库Matplotlib 3.2.1
Python金融数据处理库Pandas 1.0.2
web
# 处理时间标签 from datetime import datetime # 图形参数控制 import pylab as pl # 导入及处理数据 import pandas as pd # 绘图 import matplotlib.pyplot as plt import matplotlib as mpl # 解决一些编辑器(VSCode)或IDE(PyCharm)等存在的图片显示问题, # 应用Tkinter绘图,以便对图形进行放缩操做 mpl.use('TkAgg') # 导入数据并作处理 def import_csv(stock_code): df = pd.read_csv(stock_code + '.csv') df.rename(columns={ 'date': 'Date', 'open': 'Open', 'high': 'High', 'low': 'Low', 'close': 'Close', 'volume': 'Volume' }, inplace=True) df['Date'] = pd.to_datetime(df['Date'], format='%Y/%m/%d') df.set_index(['Date'], inplace=True) return df stock_code = 'sh600519' # 绘制数据的规模scale scale = 100 df = import_csv(stock_code)[-scale:] # EMA(Exponential Moving Average), 指数移动平均线 num_periods_fast = 10 # 快速EMA的时间周期,10 # K:平滑常数,常取2/(n+1) K_fast = 2 / (num_periods_fast + 1) # 快速EMA平滑常数 ema_fast = 0 num_periods_slow = 40 # 慢速EMA的时间周期,40 K_slow = 2 / (num_periods_slow + 1) # 慢速EMA平滑常数 ema_slow = 0 num_periods_macd = 20 # MACD EMA的时间周期,20 K_macd = 2 / (num_periods_macd + 1) # MACD EMA平滑常数 ema_macd = 0 ema_fast_values = [] ema_slow_values = [] macd_values = [] macd_signal_values = [] # MACD - MACD-EMA MACD_hist_values = [] for close_price in df['Close']: if ema_fast == 0: # 第一个值 ema_fast = close_price ema_slow = close_price else: ema_fast = (close_price - ema_fast) * K_fast + ema_fast ema_slow = (close_price - ema_slow) * K_slow + ema_slow ema_fast_values.append(ema_fast) ema_slow_values.append(ema_slow) # MACD is fast_MA - slow_EMA macd = ema_fast - ema_slow if ema_macd == 0: ema_macd = macd else: # signal is EMA of MACD values ema_macd = (macd - ema_macd) * K_macd + ema_macd macd_values.append(macd) macd_signal_values.append(ema_macd) MACD_hist_values.append(macd - ema_macd) df = df.assign(ClosePrice=pd.Series(df['Close'], index=df.index)) df = df.assign(FastEMA10d=pd.Series(ema_fast_values, index=df.index)) df = df.assign(SlowEMA40d=pd.Series(ema_slow_values, index=df.index)) df = df.assign(MACD=pd.Series(macd_values, index=df.index)) df = df.assign(EMA_MACD20d=pd.Series(macd_signal_values, index=df.index)) df = df.assign(MACD_hist=pd.Series(MACD_hist_values, index=df.index)) close_price = df['ClosePrice'] ema_f = df['FastEMA10d'] ema_s = df['SlowEMA40d'] macd = df['MACD'] ema_macd = df['EMA_MACD20d'] macd_hist = df['MACD_hist'] # 设置画布,纵向排列的三个子图 fig, ax = plt.subplots(3, 1) # 设置标签显示中文 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # 调整子图的间距,hspace表示高(height)方向的间距 plt.subplots_adjust(hspace=.1) # 设置第一子图的y轴信息及标题 ax[0].set_ylabel('Close price in ¥') ax[0].set_title('A_Stock %s MACD Indicator' % stock_code) close_price.plot(ax=ax[0], color='g', lw=1., legend=True, use_index=False) ema_f.plot(ax=ax[0], color='b', lw=1., legend=True, use_index=False) ema_s.plot(ax=ax[0], color='r', lw=1., legend=True, use_index=False) # 应用同步缩放 ax[1] = plt.subplot(312, sharex=ax[0]) macd.plot(ax=ax[1], color='k', lw=1., legend=True, sharex=ax[0], use_index=False) ema_macd.plot(ax=ax[1], color='g', lw=1., legend=True, use_index=False) # 应用同步缩放 ax[2] = plt.subplot(313, sharex=ax[0]) df['MACD_hist'].plot(ax=ax[2], color='r', kind='bar', legend=True, sharex=ax[0]) # 设置间隔,以便图形横坐标能够正常显示(不然数据多了x轴会重叠) interval = scale // 20 # 设置x轴参数,应用间隔设置 # 时间序列转换,(不然日期默认会显示时分秒数据00:00:00) # x轴标签旋转便于显示 pl.xticks([i for i in range(1, scale + 1, interval)], [datetime.strftime(i, format='%Y-%m-%d') for i in \ pd.date_range(df.index[0], df.index[-1], freq='%dd' % (interval))], rotation=45) plt.show()
所得图像以下:
算法
本文以Python
的Matplotlib
绘图库为工具,实现了金融领域经常使用的MACD技术指标,便于你们更好地理解和应用量化交易,往后还会更新其余技术指标的Python
实现,欢迎学习交流!
本文用到的数据及有关书籍资源有须要者可私信我。app
[1] Sebastien Donadio,Sourav Ghosh.Learn Algorithmic Trading - Fundamentals of Algorithmic Trading.Birmingham:Packt Press,2019.P55-59.编辑器
指出了文中的一个错误,已在文中修改。代码第71行应该为K_macd,为macd的EMA的平滑常数,在此感谢细心的读者@ertewu.学习