我们当前的代码是:

    现在我认为向我们的移动均值添加自定义填充是一个很好的主意。 移动均值通常用于说明价格趋势。 这个想法是,你可以计算一个快速和一个慢速的移动均值。 一般来说,移动均值用于使价格变得『平滑』。 他们总是『滞后』于价格,但是我们的想法是计算不同的速度。 移动均值越大就越『慢』。 所以这个想法是,如果『较快』的移动均值超过『较慢』的均值,那么价格就会上升,这是一件好事。 如果较快的 MA 从较慢的 MA 下方穿过,则这是下降趋势并且通常被视为坏事。 我的想法是在快速和慢速 MA 之间填充,『上升』趋势为绿色,然后下降趋势为红色。 方法如下:

    1. where=(ma1[-start:] < ma2[-start:]),
    2. facecolor='r', edgecolor='r', alpha=0.5)
    3. ax3.fill_between(date[-start:], ma2[-start:], ma1[-start:],
    4. where=(ma1[-start:] > ma2[-start:]),
    5. facecolor='g', edgecolor='g', alpha=0.5)

    这里,我们剪切和粘贴ax2日期格式,然后我们将x刻度标签设置为false,去掉它们!

    我们还可以通过在轴域定义中执行以下操作,为每个轴域提供自定义标签:

    1. fig = plt.figure()
    2. ax1 = plt.subplot2grid((6,1), (0,0), rowspan=1, colspan=1)
    3. plt.title(stock)
    4. ax2 = plt.subplot2grid((6,1), (1,0), rowspan=4, colspan=1)
    5. plt.xlabel('Date')
    6. plt.ylabel('Price')
    7. ax3 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1)

    所以,这里发生的是,我们通过首先将nbins设置为 5 来修改我们的y轴对象。这意味着我们显示的标签最多为 5 个。然后我们还可以『修剪』标签,因此,在我们这里, 我们修剪底部标签,这会使它消失,所以现在不会有任何文本重叠。 我们仍然可能打算修剪ax2的顶部标签,但这里是我们目前为止的源代码:

    当前的源码:

    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 bytesconverter
    25. fig = plt.figure()
    26. ax1 = plt.subplot2grid((6,1), (0,0), rowspan=1, colspan=1)
    27. plt.title(stock)
    28. plt.ylabel('H-L')
    29. ax2 = plt.subplot2grid((6,1), (1,0), rowspan=4, colspan=1)
    30. plt.ylabel('Price')
    31. ax3 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1)
    32. plt.ylabel('MAvgs')
    33. stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1y/csv'
    34. source_code = urllib.request.urlopen(stock_price_url).read().decode()
    35. stock_data = []
    36. split_source = source_code.split('\n')
    37. for line in split_source:
    38. split_line = line.split(',')
    39. if len(split_line) == 6:
    40. if 'values' not in line and 'labels' not in line:
    41. stock_data.append(line)
    42. date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data,
    43. delimiter=',',
    44. unpack=True,
    45. converters={0: bytespdate2num('%Y%m%d')})
    46. x = 0
    47. y = len(date)
    48. ohlc = []
    49. while x < y:
    50. append_me = date[x], openp[x], highp[x], lowp[x], closep[x], volume[x]
    51. ohlc.append(append_me)
    52. x+=1
    53. ma1 = moving_average(closep,MA1)
    54. ma2 = moving_average(closep,MA2)
    55. start = len(date[MA2-1:])
    56. h_l = list(map(high_minus_low, highp, lowp))
    57. ax1.plot_date(date,h_l,'-')
    58. ax1.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='lower'))
    59. ax2.grid(True)
    60. bbox_props = dict(boxstyle='round',fc='w', ec='k',lw=1)
    61. ax2.annotate(str(closep[-1]), (date[-1], closep[-1]),
    62. xytext = (date[-1]+4, closep[-1]), bbox=bbox_props)
    63. ## # Annotation example with arrow
    64. ## ax2.annotate('Bad News!',(date[11],highp[11]),
    65. ## xytext=(0.8, 0.9), textcoords='axes fraction',
    66. ## arrowprops = dict(facecolor='grey',color='grey'))
    67. ##
    68. ##
    69. ## # Font dict example
    70. ## font_dict = {'family':'serif',
    71. ## 'color':'darkred',
    72. ## 'size':15}
    73. ## # Hard coded text
    74. ## ax2.text(date[10], closep[1],'Text Example', fontdict=font_dict)
    75. ax3.plot(date[-start:], ma1[-start:], linewidth=1)
    76. ax3.plot(date[-start:], ma2[-start:], linewidth=1)
    77. ax3.fill_between(date[-start:], ma2[-start:], ma1[-start:],
    78. where=(ma1[-start:] < ma2[-start:]),
    79. facecolor='r', edgecolor='r', alpha=0.5)
    80. ax3.fill_between(date[-start:], ma2[-start:], ma1[-start:],
    81. where=(ma1[-start:] > ma2[-start:]),
    82. facecolor='g', edgecolor='g', alpha=0.5)
    83. ax3.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    84. ax3.xaxis.set_major_locator(mticker.MaxNLocator(10))
    85. for label in ax3.xaxis.get_ticklabels():
    86. label.set_rotation(45)
    87. plt.setp(ax1.get_xticklabels(), visible=False)
    88. plt.setp(ax2.get_xticklabels(), visible=False)
    89. plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90, wspace=0.2, hspace=0)
    90. plt.show()
    91. graph_data('EBAY')

    看起来好了一些,但是仍然有一些东西需要清除。