[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:
- Read quote of two stocks from Google Finance
- Draw their trending.
- 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
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))
ymin = 0 ymax = max(ax.get_ylim(), ax2.get_ylim()) 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
Highlight the lowest and highest prices
-> See here for completed code.
Originally published at 126.96.36.199 on November 29, 2015.