Getting Stock Prices from Yahoo and plotting Python 3 Matplolib Urllib
This is some quick notes about getting stock data from Yahoo and plotting it using Matplotlib . The Python version used is Python 3.5
Credits to sentdex. You can check him out on Youtube.
1 2 3 4 5 6 7 8 9 |
import matplotlib.pyplot as plt import numpy as np import urllib import matplotlib.dates as mdate import urllib.request %matplotlib inline #%matplotlib qt #%matplotlib notebook # interactive popout window plot |
1 2 3 4 5 6 7 8 9 |
#getting data from the internet #define our converter function def bytespdate2num(fmt, encoding='utf-8'): strconverter = mdate.strpdate2num(fmt) def bytesconverter(b): s = b.decode(encoding) return strconverter(s) return bytesconverter |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#define a function which will take the stock data and plot the graph def graph_data(stock): stock_data_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=10y/csv' source_code = urllib.request.urlopen(stock_data_url).read().decode() stock_data =[] split_source = source_code.split('\n') #split the code based on next line #lets grab only the relevant stock data for line in split_source: split_line = line.split(',') if(len(split_line))==6: if 'values' not in line and 'labels' not in line: stock_data.append(line) date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data, delimiter=',',unpack=True, converters={0: bytespdate2num('%Y%m%d')}) plt.plot_date(date,closep,'-', label='Price') plt.xlabel('Date') plt.ylabel('Price') plt.title('Interesting stock graph from yahoo') plt.legend() |
1 2 |
#lets plot TSLA stock prices. graph_data('TSLA') |