二十一、更多指标数据

在这篇 Matplotlib 教程中,我们介绍了添加一些简单的函数来计算数据,以便我们填充我们的轴域。 一个是简单的移动均值,另一个是简单的价格 HML 计算。

这些新函数是:

  1. def moving_average(values, window):
  2. weights = np.repeat(1.0, window)/window
  3. smas = np.convolve(values, weights, 'valid')
  4. return smas
  5. def high_minus_low(highs, lows):
  6. return highs-lows

你不需要太过专注于理解移动均值的工作原理,我们只是对样本数据来计算它,以便可以学习更多自定义 Matplotlib 的东西。

我们还想在脚本顶部为移动均值定义一些值:

  1. MA1 = 10
  2. MA2 = 30

下面,在我们的graph_data函数中:

  1. ma1 = moving_average(closep,MA1)
  2. ma2 = moving_average(closep,MA2)
  3. start = len(date[MA2-1:])
  4. h_l = list(map(high_minus_low, highp, lowp))

在这里,我们计算两个移动均值和 HML。

我们还定义了一个『起始』点。 我们这样做是因为我们希望我们的数据排成一行。 例如,20 天的移动均值需要 20 个数据点。 这意味着我们不能在第 5 天真正计算 20 天的移动均值。 因此,当我们计算移动均值时,我们会失去一些数据。 为了处理这种数据的减法,我们使用起始变量来计算应该有多少数据。 这里,我们可以安全地使用[-start:]绘制移动均值,并且如果我们希望的话,对所有绘图进行上述步骤来排列数据。

接下来,我们可以在ax1上绘制 HML,通过这样:

  1. ax1.plot_date(date,h_l,'-')

最后我们可以通过这样向ax3添加移动均值:

  1. ax3.plot(date[-start:], ma1[-start:])
  2. ax3.plot(date[-start:], ma2[-start:])

我们的完整代码,包括增加我们所用的时间范围:

  1. import matplotlib.pyplot as plt
  2. import matplotlib.dates as mdates
  3. import matplotlib.ticker as mticker
  4. from matplotlib.finance import candlestick_ohlc
  5. from matplotlib import style
  6. import numpy as np
  7. import urllib
  8. import datetime as dt
  9. style.use('fivethirtyeight')
  10. print(plt.style.available)
  11. print(plt.__file__)
  12. MA1 = 10
  13. MA2 = 30
  14. def moving_average(values, window):
  15. weights = np.repeat(1.0, window)/window
  16. smas = np.convolve(values, weights, 'valid')
  17. return smas
  18. def high_minus_low(highs, lows):
  19. return highs-lows
  20. def bytespdate2num(fmt, encoding='utf-8'):
  21. strconverter = mdates.strpdate2num(fmt)
  22. def bytesconverter(b):
  23. s = b.decode(encoding)
  24. return strconverter(s)
  25. return bytesconverter
  26. def graph_data(stock):
  27. fig = plt.figure()
  28. ax1 = plt.subplot2grid((6,1), (0,0), rowspan=1, colspan=1)
  29. plt.title(stock)
  30. ax2 = plt.subplot2grid((6,1), (1,0), rowspan=4, colspan=1)
  31. plt.xlabel('Date')
  32. plt.ylabel('Price')
  33. ax3 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1)
  34. stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1y/csv'
  35. source_code = urllib.request.urlopen(stock_price_url).read().decode()
  36. stock_data = []
  37. split_source = source_code.split('\n')
  38. for line in split_source:
  39. split_line = line.split(',')
  40. if len(split_line) == 6:
  41. if 'values' not in line and 'labels' not in line:
  42. stock_data.append(line)
  43. date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data,
  44. delimiter=',',
  45. unpack=True,
  46. converters={0: bytespdate2num('%Y%m%d')})
  47. x = 0
  48. y = len(date)
  49. ohlc = []
  50. while x < y:
  51. append_me = date[x], openp[x], highp[x], lowp[x], closep[x], volume[x]
  52. ohlc.append(append_me)
  53. x+=1
  54. ma1 = moving_average(closep,MA1)
  55. ma2 = moving_average(closep,MA2)
  56. start = len(date[MA2-1:])
  57. h_l = list(map(high_minus_low, highp, lowp))
  58. ax1.plot_date(date,h_l,'-')
  59. candlestick_ohlc(ax2, ohlc, width=0.4, colorup='#77d879', colordown='#db3f3f')
  60. for label in ax2.xaxis.get_ticklabels():
  61. label.set_rotation(45)
  62. ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
  63. ax2.xaxis.set_major_locator(mticker.MaxNLocator(10))
  64. ax2.grid(True)
  65. bbox_props = dict(boxstyle='round',fc='w', ec='k',lw=1)
  66. ax2.annotate(str(closep[-1]), (date[-1], closep[-1]),
  67. xytext = (date[-1]+4, closep[-1]), bbox=bbox_props)
  68. ## # Annotation example with arrow
  69. ## ax2.annotate('Bad News!',(date[11],highp[11]),
  70. ## xytext=(0.8, 0.9), textcoords='axes fraction',
  71. ## arrowprops = dict(facecolor='grey',color='grey'))
  72. ##
  73. ##
  74. ## # Font dict example
  75. ## font_dict = {'family':'serif',
  76. ## 'color':'darkred',
  77. ## 'size':15}
  78. ## # Hard coded text
  79. ## ax2.text(date[10], closep[1],'Text Example', fontdict=font_dict)
  80. ax3.plot(date[-start:], ma1[-start:])
  81. ax3.plot(date[-start:], ma2[-start:])
  82. plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90, wspace=0.2, hspace=0)
  83. plt.show()
  84. graph_data('EBAY')

代码效果如图:

二十一、更多指标数据 - 图1