分享

用matplotlib高仿同花顺的K线,成交量,MACD,KDJ(一)

 昱雄藏书 2021-12-23

开发环境:python v3.8.2, matplotlib v3.2.1, VSCode

    开始学量化2,3周了,python也还是新手,这2天才开始看一下matplotlib的用法,网上搜了一些K线图的绘制,大多采用mpl_finance绘制的K线图,效果都一般般,昨天心血来潮,一边学习matplotlib,一边自己高仿了一个同花顺的效果,鼠标交互还没做(下次有时间再做),怕代码太长。本来用mpl_finance的新版本的,确实对K线图支持的好些了,但是代码限的比较死,不好在后面添加子图,所以直接从里面套用了部分代码,先把结果贴上来。代码标注的很详细,我就不解释了,直接看代码。

 

  1. # -*- coding:utf-8 -*-
  2. import tushare as ts # 获取股票数据用
  3. import numpy as np
  4. import pandas as pd
  5. import matplotlib.pyplot as plt
  6. import matplotlib.ticker as ticker # 用于日期刻度定制
  7. # import mpl_finance as mpf
  8. # 注释了上面一行的旧版,新版是mplfinance,少了一个下划线,运行没警告,新版绘制蜡烛图性能应该更高,但是限得比较死,
  9. # 不好加子图,后面我们把关键代码拿出来自己绘制
  10. from mplfinance import original_flavor as mpf # 用新版库里面的旧版实现(跟mpl_finance一模一样)
  11. from matplotlib import colors as mcolors # 用于颜色转换成渲染时顶点需要的颜色格式
  12. from matplotlib.collections import LineCollection, PolyCollection # 用于绘制直线集合和多边形集合
  13. import tools # 计算MACD和KDJ(没有使用talib,有缺陷)
  14. # 获取数据
  15. df = ts.get_k_data('603986', '2019-01-01') # 获取日K线数据
  16. df.drop('code', axis=1, inplace=True) # 剔除多余的列
  17. tools.calc_macd(df) # 计算MACD值,数据存于DataFrame中
  18. tools.calc_kdj(df) # 计算KDJ值,数据存于DataFrame中
  19. df = df[-150:] # 取最近的N天测试,列顺序为 date,open,close,high,low,volume,dif,dea,bar,k,d,j
  20. # 日期转换成整数序列
  21. date_tickers=df.date.values
  22. df.date = range(0, len(df)) # 日期改变成序号
  23. matix = df.values # 转换成绘制蜡烛图需要的数据格式(date, open, close, high, low, volume)
  24. xdates = matix[:, 0] # X轴数据(这里用的天数索引)
  25. # 设置外观效果
  26. plt.rc('font', family='Microsoft YaHei') # 用中文字体,防止中文显示不出来
  27. plt.rc('figure', fc='k') # 绘图对象背景图
  28. plt.rc('text', c='#800000') # 文本颜色
  29. plt.rc('axes', axisbelow=True, xmargin=0, fc='k', ec='#800000', lw=1.5, labelcolor='#800000', unicode_minus=False) # 坐标轴属性(置底,左边无空隙,背景色,边框色,线宽,文本颜色,中文负号修正)
  30. plt.rc('xtick', c='#d43221') # x轴刻度文字颜色
  31. plt.rc('ytick', c='#d43221') # y轴刻度文字颜色
  32. plt.rc('grid', c='#800000', alpha=0.9, ls=':', lw=0.8) # 网格属性(颜色,透明值,线条样式,线宽)
  33. plt.rc('lines', lw=0.8) # 全局线宽
  34. # 创建绘图对象和4个坐标轴
  35. fig = plt.figure(figsize=(16, 8))
  36. left, width = 0.05, 0.9
  37. ax1 = fig.add_axes([left, 0.6, width, 0.35]) # left, bottom, width, height
  38. ax2 = fig.add_axes([left, 0.45, width, 0.15], sharex=ax1) # 共享ax1轴
  39. ax3 = fig.add_axes([left, 0.25, width, 0.2], sharex=ax1) # 共享ax1轴
  40. ax4 = fig.add_axes([left, 0.05, width, 0.2], sharex=ax1) # 共享ax1轴
  41. plt.setp(ax1.get_xticklabels(), visible=False) # 使x轴刻度文本不可见,因为共享,不需要显示
  42. plt.setp(ax2.get_xticklabels(), visible=False) # 使x轴刻度文本不可见,因为共享,不需要显示
  43. plt.setp(ax3.get_xticklabels(), visible=False) # 使x轴刻度文本不可见,因为共享,不需要显示
  44. # 绘制蜡烛图
  45. def format_date(x, pos=None): return '' if x<0 or x>len(date_tickers)-1 else date_tickers[int(x)] # 日期格式化函数,根据天数索引取出日期值
  46. ax1.xaxis.set_major_formatter(ticker.FuncFormatter(format_date)) # 设置自定义x轴格式化日期函数
  47. ax1.xaxis.set_major_locator(ticker.MultipleLocator(max(int(len(df)/15), 5))) # 横向最多排15个左右的日期,最少5个,防止日期太拥挤
  48. # mpf.candlestick_ochl(ax1, matix, width=0.5, colorup='#ff3232', colordown='#54fcfc')
  49. # # 下面这一段代码,替换了上面注释的这个函数,因为上面的这个函数达不到同花顺的效果
  50. opens, closes, highs, lows = matix[:, 1], matix[:, 2], matix[:, 3], matix[:, 4] # 取出ochl值
  51. avg_dist_between_points = (xdates[-1] - xdates[0]) / float(len(xdates)) # 计算每个日期之间的距离
  52. delta = avg_dist_between_points / 4.0 # 用于K线实体(矩形)的偏移坐标计算
  53. barVerts = [((date - delta, open), (date - delta, close), (date + delta, close), (date + delta, open)) for date, open, close in zip(xdates, opens, closes) ] # 生成K线实体(矩形)的4个顶点坐标
  54. rangeSegLow = [ ((date, low), (date, min(open, close))) for date, low, open, close in zip(xdates, lows, opens, closes) ] # 生成下影线顶点列表
  55. rangeSegHigh = [ ((date, high), (date, max(open, close))) for date, high, open, close in zip(xdates, highs, opens, closes) ] # 生成上影线顶点列表
  56. rangeSegments = rangeSegLow + rangeSegHigh # 上下影线顶点列表
  57. cmap = {True: mcolors.to_rgba('#000000', 1.0), False: mcolors.to_rgba('#54fcfc', 1.0)} # K线实体(矩形)中间的背景色(True是上涨颜色,False是下跌颜色)
  58. inner_colors = [ cmap[opn < cls] for opn, cls in zip(opens, closes) ] # K线实体(矩形)中间的背景色列表
  59. cmap = {True: mcolors.to_rgba('#ff3232', 1.0), False: mcolors.to_rgba('#54fcfc', 1.0)} # K线实体(矩形)边框线颜色(上下影线和后面的成交量颜色也共用)
  60. updown_colors = [ cmap[opn < cls] for opn, cls in zip(opens, closes) ] # K线实体(矩形)边框线颜色(上下影线和后面的成交量颜色也共用)列表
  61. ax1.add_collection(LineCollection(rangeSegments, colors=updown_colors, linewidths=0.5, antialiaseds=False)) # 生成上下影线的顶点数据(颜色,线宽,反锯齿,反锯齿关闭好像没效果)
  62. ax1.add_collection(PolyCollection(barVerts, facecolors=inner_colors, edgecolors=updown_colors, antialiaseds=False, linewidths=0.5)) # 生成多边形(矩形)顶点数据(背景填充色,边框色,反锯齿,线宽)
  63. # 绘制均线
  64. mav_colors = ['#ffffff', '#d4ff07', '#ff80ff', '#00e600', '#02e2f4', '#ffffb9', '#2a6848'] # 均线循环颜色
  65. mav_period = [5, 10, 20, 30, 60, 120, 180] # 定义要绘制的均线周期,可增减
  66. n = len(df)
  67. for i in range(len(mav_period)):
  68. if n >= mav_period[i]:
  69. mav_vals = df['close'].rolling(mav_period[i]).mean().values
  70. ax1.plot(xdates, mav_vals, c=mav_colors[i%len(mav_colors)], label='MA'+str(mav_period[i]))
  71. ax1.set_title('K线图') # 标题
  72. ax1.grid(True) # 画网格
  73. ax1.legend(loc='upper right') # 图例放置于右上角
  74. ax1.xaxis_date() # 好像要不要效果一样?
  75. # 绘制成交量和成交量均线(5日,10日)
  76. # ax2.bar(xdates, matix[:, 5], width= 0.5, color=updown_colors) # 绘制成交量柱状图
  77. barVerts = [((date - delta, 0), (date - delta, vol), (date + delta, vol), (date + delta, 0)) for date, vol in zip(xdates, matix[:,5]) ] # 生成K线实体(矩形)的4个顶点坐标
  78. ax2.add_collection(PolyCollection(barVerts, facecolors=inner_colors, edgecolors=updown_colors, antialiaseds=False, linewidths=0.5)) # 生成多边形(矩形)顶点数据(背景填充色,边框色,反锯齿,线宽)
  79. if n>=5: # 5日均线,作法类似前面的均线
  80. vol5 = df['volume'].rolling(5).mean().values
  81. ax2.plot(xdates, vol5, c='y', label='VOL5')
  82. if n>=10: # 10日均线,作法类似前面的均线
  83. vol10 = df['volume'].rolling(10).mean().values
  84. ax2.plot(xdates, vol10, c='w', label='VOL10')
  85. ax2.yaxis.set_ticks_position('right') # y轴显示在右边
  86. ax2.legend(loc='upper right') # 图例放置于右上角
  87. ax2.grid(True) # 画网格
  88. # ax2.set_ylabel('成交量') # y轴名称
  89. # 绘制MACD
  90. difs, deas, bars = matix[:, 6], matix[:, 7], matix[:, 8] # 取出MACD值
  91. ax3.axhline(0, ls='-', c='g', lw=0.5) # 水平线
  92. ax3.plot(xdates, difs, c='w', label='DIFF') # 绘制DIFF线
  93. ax3.plot(xdates, deas, c='y', label='DEA') # 绘制DEA线
  94. # ax3.bar(xdates, df['bar'], width= 0.05, color=bar_colors) # 绘制成交量柱状图(发现用bar绘制,线的粗细不一致,故使用下面的直线列表)
  95. cmap = {True: mcolors.to_rgba('r', 1.0), False: mcolors.to_rgba('g', 1.0)} # MACD线颜色,大于0为红色,小于0为绿色
  96. bar_colors = [ cmap[bar > 0] for bar in bars ] # MACD线颜色列表
  97. vlines = [ ((date, 0), (date, bars[date])) for date in range(len(bars)) ] # 生成MACD线顶点列表
  98. ax3.add_collection(LineCollection(vlines, colors=bar_colors, linewidths=0.5, antialiaseds=False)) # 生成MACD线的顶点数据(颜色,线宽,反锯齿)
  99. ax3.legend(loc='upper right') # 图例放置于右上角
  100. ax3.grid(True) # 画网格
  101. # 绘制KDJ
  102. K, D, J = matix[:, 9], matix[:, 10], matix[:, 11] # 取出KDJ值
  103. ax4.axhline(0, ls='-', c='g', lw=0.5) # 水平线
  104. ax4.yaxis.set_ticks_position('right') # y轴显示在右边
  105. ax4.plot(xdates, K, c='y', label='K') # 绘制K线
  106. ax4.plot(xdates, D, c='c', label='D') # 绘制D线
  107. ax4.plot(xdates, J, c='m', label='J') # 绘制J线
  108. ax4.legend(loc='upper right') # 图例放置于右上角
  109. ax4.grid(True) # 画网格
  110. # set useblit = True on gtkagg for enhanced performance
  111. from matplotlib.widgets import Cursor # 处理鼠标
  112. cursor = Cursor(ax1, useblit=True, color='w', linewidth=0.5, linestyle='--')
  113. plt.show()

 

代码中用到了tools库,自己的,我把那2个计算函数贴出来,你们直接替换即可

 

  1. # 在k线基础上计算MACD,并将结果存储在df上面(dif,dea,bar)
  2. def calc_macd(df, fastperiod=12, slowperiod=26, signalperiod=9):
  3. ewma12 = df['close'].ewm(span=fastperiod,adjust=False).mean()
  4. ewma26 = df['close'].ewm(span=slowperiod,adjust=False).mean()
  5. df['dif'] = ewma12-ewma26
  6. df['dea'] = df['dif'].ewm(span=signalperiod,adjust=False).mean()
  7. df['bar'] = (df['dif']-df['dea'])*2
  8. # df['macd'] = 0
  9. # series = df['dif']>0
  10. # df.loc[series[series == True].index, 'macd'] = 1
  11. return df
  12. # 在k线基础上计算KDF,并将结果存储在df上面(k,d,j)
  13. def calc_kdj(df):
  14. low_list = df['low'].rolling(9, min_periods=9).min()
  15. low_list.fillna(value=df['low'].expanding().min(), inplace=True)
  16. high_list = df['high'].rolling(9, min_periods=9).max()
  17. high_list.fillna(value=df['high'].expanding().max(), inplace=True)
  18. rsv = (df['close'] - low_list) / (high_list - low_list) * 100
  19. df['k'] = pd.DataFrame(rsv).ewm(com=2).mean()
  20. df['d'] = df['k'].ewm(com=2).mean()
  21. df['j'] = 3 * df['k'] - 2 * df['d']
  22. # df['kdj'] = 0
  23. # series = df['k']>df['d']
  24. # df.loc[series[series == True].index, 'kdj'] = 1
  25. # # df.loc[series[(series == True) & (series.shift() == False)].index, 'kdjcross'] = 1
  26. # # df.loc[series[(series == False) & (series.shift() == True)].index, 'kdjcross'] = -1
  27. return df

转载请注明出处:https://blog.csdn.net/PeakGao/article/details/105634317

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多