Quant500 Academy

7. Visualizing data with matplotlib: your first price chart

Level 2: Python from Scratch for Finance

A single number almost never tells the whole story; a chart almost always does. Matplotlib is Python's standard charting library, and although it has a quick MATLAB-style interface, the recommended way to use it — especially once your code starts to grow — is its object-oriented interface.

import matplotlib.pyplot as plt
import numpy as np

days = np.arange(0, 30)
prices = 180 + np.cumsum(np.random.randn(30))  # simple simulation of a random walk of prices

The central idea of the object-oriented interface is that, instead of drawing onto an implicit global state, you explicitly create a Figure object (the whole canvas) and one or more Axes objects (the axes where the drawing actually happens), and you call methods on them. The most practical way to create both at once is plt.subplots():

fig, ax = plt.subplots(figsize=(10, 5))

ax.plot(days, prices, color="tab:blue", label="Simulated price")
ax.set_xlabel("Day")
ax.set_ylabel("Price")
ax.set_title("Simulated price evolution")
ax.legend()

plt.show()

This explicit style — working on fig and ax instead of on standalone functions such as plain plot() — becomes essential as soon as you need more than one chart in the same figure, which is common when comparing several assets or several metrics at once:

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(14, 5))

axes[0].plot(days, prices, color="tab:blue")
axes[0].set_title("Price")

returns = np.diff(prices) / prices[:-1]
axes[1].plot(days[1:], returns, color="tab:red")
axes[1].set_title("Daily return")

fig.tight_layout()
plt.show()

When you define more than one series on the same chart, using the label argument in each plot() and then calling ax.legend() with no arguments is more robust than passing the names by hand to legend(): if you later add or remove a series, the legend updates itself instead of drifting out of sync.

fig, ax = plt.subplots(figsize=(10, 5))

ax.plot(days, prices, label="Strategy A")
ax.plot(days, prices * 1.02, label="Strategy B")  # illustrative example
ax.legend(loc=0)   # loc=0 lets matplotlib choose the best position automatically

plt.show()

And to save the result to a file, rather than just showing it on screen, the method is savefig on the fig object, not on plt:

fig.savefig("price_evolution.png", dpi=200)

With this you already have the essentials to go from a list of numbers to a readable chart — which is, in practice, the first step of any exploratory analysis before building a single strategy.

The rest of Quant500

What you are learning, applied to the index every day:

The model portfolio, weekly in your inbox

Every Saturday, its week in one minute: how it went, the best and the worst, and which insiders bought with their own money. Plus, the day the model is rebuilt, which stocks come in and which go out. A simulation, not advice. At most one email a week, no ads, no account; one-click unsubscribe. Made by one person: Pol Gracia.

A model portfolio with simulated results, not a personalized recommendation. Your email is used for this only: privacy.

Behind the Academy and the rest of Quant500 there is one person: Pol Gracia Serrahima.