Matplotlib – plotting stock prices

I was playing the other day with Matplotlib. I was amazed how easy it is to plot graphs, all with the builtin browser.

Say you want to plot some stock data. You can download a sample provided by EOD data site. They give a sample for AAPL prices, which can be downloaded from here. If you unzip, you’ll get a NASDAQ_AAPL.txt file, which actually is a csv.

Installation

Installing matplotlib is simple with pip:

$ pip install matplotlib

Plotting

Here’s a very short python code to read and plot it:

import matplotlib
matplotlib.use('webagg')

import matplotlib.pyplot as plt
import csv

with open('etc/NASDAQ_AAPL.txt') as inf:
  csvr = csv.reader(inf)
  csvr.next()
  prices = [float(row[2]) for row in csvr]
  
plt.title('AAPL prices')
plt.xlabel('Time')
plt.ylabel('Price')

plt.plot(prices)
plt.grid(True)
plt.show()

Walkthrough:

import matplotlib
matplotlib.use('webagg')

Imports matplotlib and sets the default backend used for plotting to WebAgg.

import matplotlib.pyplot as plt
import csv

with open('etc/NASDAQ_AAPL.txt') as inf:
  csvr = csv.reader(inf)
  csvr.next()
  prices = [float(row[2]) for row in csvr]

Import plotting part of matplotlib and the standard Python csv library. Read the file, skip the header and pick open prices (3rd column in the CSV file).

plt.title('AAPL prices')
plt.xlabel('Time')
plt.ylabel('Price')
plt.grid(True)

plt.plot(prices)
plt.show()

Set the title, X and Y axis labels of the plot and specify that plot should have the grid shown. Actually perform plotting and show it.

There’s a minor issue for which I filed a report here, but after manually updating the file as per the ticket, all seems to be working just fine.

After doing:

$ python matplotlib_prb.py

It will start a server and open your browser pointing to http://127.0.0.1:8988/.

Final plot

Here’s how it looks for the above file:

plot