zero_shubham1

matplotlib_datecoversion

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