九、时间戳的转换

本教程的重点是将来自 Yahoo finance API 的日期转换为 Matplotlib 可理解的日期。 为了实现它,我们要写一个新的函数,bytespdate2num

  1. def bytespdate2num(fmt, encoding='utf-8'):
  2. strconverter = mdates.strpdate2num(fmt)
  3. def bytesconverter(b):
  4. s = b.decode(encoding)
  5. return strconverter(s)
  6. return bytesconverter

此函数接受数据,基于编码来解码数据,然后返回它。

将此应用于我们的程序的其余部分:

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import urllib
  4. import matplotlib.dates as mdates
  5. def bytespdate2num(fmt, encoding='utf-8'):
  6. strconverter = mdates.strpdate2num(fmt)
  7. def bytesconverter(b):
  8. s = b.decode(encoding)
  9. return strconverter(s)
  10. return bytesconverter
  11. def graph_data(stock):
  12. stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=10y/csv'
  13. source_code = urllib.request.urlopen(stock_price_url).read().decode()
  14. stock_data = []
  15. split_source = source_code.split('\n')
  16. for line in split_source:
  17. split_line = line.split(',')
  18. if len(split_line) == 6:
  19. if 'values' not in line and 'labels' not in line:
  20. stock_data.append(line)
  21. date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data,
  22. delimiter=',',
  23. unpack=True,
  24. # %Y = full year. 2015
  25. # %y = partial year 15
  26. # %m = number month
  27. # %d = number day
  28. # %H = hours
  29. # %M = minutes
  30. # %S = seconds
  31. # 12-06-2014
  32. # %m-%d-%Y
  33. converters={0: bytespdate2num('%Y%m%d')})
  34. plt.plot_date(date, closep,'-', label='Price')
  35. plt.xlabel('Date')
  36. plt.ylabel('Price')
  37. plt.title('Interesting Graph\nCheck it out')
  38. plt.legend()
  39. plt.show()
  40. graph_data('TSLA')

如果你绘制 TSLA,结果图应该看起来像这样:

九、时间戳的转换 - 图1