[code] Compare two stocks by pyplot

One of my colleagues in my former company left the job then joined another company in the beginning of this year, and I found there is a dramatic change on these two companies until today. Therefore, I made a plot as shown above (sorry for making fun of it lol) to ask him what happened.

By using matplotlib.pyplot and pandas.DataFrame, I:

  1. Read quote of two stocks from Google Finance
  2. Draw their trending.
  3. Plot a vertical line to indicate when my ex-colleague’s changed the company, and highlight the highest and lowest prices.

Read the recent 1-year stock prices from Google Finance

1

from matplotlib import pyplot as plt from pandas.io.data import DataReader from datetime import datetime end = datetime.now() start = datetime(end.year-1, end.month, end.day) stock_label1 = ‘QUOTE_LABEL_HERE’ stock_label2 = ‘QUOTE_LABEL_2_HERE’ comp1 = DataReader(stock_label1, ‘google’, start, end) comp2 = DataReader(stock_label2, ‘google’, start, end)

Plot the stock prices overtime

After getting two pandas.DataFrame, I added another column named adj_close so I could easily compare two stocks as they have different price ranges to be putting in y-axis.

comp1_mean = comp1[‘Close’].mean() comp2_mean = comp2[‘Close’].mean() comp1[‘adj_close’] = comp1[‘Close’] / comp1_mean comp2[‘adj_close’] = comp2[‘Close’] / comp2_mean ax = comp1[‘adj_close’].plot(legend=True, label=stock_label1, figsize=(10, 4)) ax2 = comp2[‘adj_close’].plot(legend=True, label=stock_label2, figsize=(10, 4))

1

ymin = 0 ymax = max(ax.get_ylim()[1], ax2.get_ylim()[1]) exit_date = datetime(2015, 1, 9) plt.vlines(x=exit_date, ymin=ymin, ymax=ymax, label=str(exit_date)[:10], color=’r’)

Prevent legend from hiding the plot

(ref: http://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot)

Highlight the lowest and highest prices

-> See here for completed code.


Originally published at 45.55.83.242 on November 29, 2015.