Matplotlib Tutorial Part 08 - Loading Data from Internet


In [10]:
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import urllib
stock = "EBAY"

Data Conversion Function


In [11]:
# Not needed in Python2.7
def bytespdate2num(fmt, encoding='utf-8'):
    strconverter = mdates.strpdate2num(fmt)
    def bytesconverter(b):
        s = b.decode(encoding)
        return strconverter(s)
    return bytesconverter

Getting and Cleaning data


In [12]:
# Yahoo Finance API
stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/' +stock+ '/chartdata;type=quote;range=10y/csv'

# Getting Data from Yahoo Finance API
source_code = urllib.request.urlopen(stock_price_url).read().decode()

# Cleaning Data
stock_data = []    
split_source = source_code.split('\n')

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)

# Unpacking Data
date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data,
                                                      delimiter=',',
                                                      unpack=True,
                                                      converters={0: bytespdate2num('%Y%m%d')})

Plotting Points


In [13]:
fig = plt.figure(figsize=(17,9))

# Plotting
plt.plot_date(date, closep,".")

plt.xlabel('Date')
plt.ylabel('Price')
plt.title(stock)

plt.grid(True)
plt.show()


Plotting Lines


In [14]:
fig = plt.figure(figsize=(17,9))

# Plotting
plt.plot_date(date, closep,"-")

plt.xlabel('Date')
plt.ylabel('Price')
plt.title(stock)

plt.grid(True)
plt.show()