PricePlot.py
Description: PricePlot.py downloads price data from Yahoo Finance and generates multiple price and returns plots to help you visualise trends.
Define a function called PricePlot() as well as which stocks you want to analyse and over what time period. The variable symbols_list is a list of the stock tickers you want to examine. Note that the tickers you add in the list should be the same tickers used by Yahoo Finance, since this script retrieves data from there. So make sure you have the correct ticker name. For this exercise, I use four stocks ( AA: Alcoa Inc, AAPL: Apple Inc, MCD: McDonald’s Corporation, and YHOO: Yahoo! Inc.) Add the start and end dates for your study. The datetime library transforms your input into a date format.
Next, I use the Yahoo Finance downloader provided by Pandas to download historical prices of all stock tickers in the list symbols_list. Note that I indicate that I want adjusted closing prices using ['Adj Close'] since the DataReader downloads other information as well including Open, Close, High, Low and Volume for each stock.
Once the time-series of prices are downloaded, we start by plotting the adjusted closing prices of all four stocks on the same graph in order to visualise price trends.
The resulting chart is saved as AdjustedClose.png and should look like this
In order to visualise the change in the prices of each stock over time relative to the initial stock price, I normalise prices by dividing all historical prices by the initial price. This data is saved in a data frame called
data_normalized.
Similar to the previous chart, I plot the relative prices and obtain a chart that looks like this
In order to visualise stock returns over a certain period of time, such as 30 days, we first calculate stock returns in a new data frame called
data_ret. To do so, we divide the price at time t by the price at time t-1, and this can be easily achieved using the
.shift() function in Pandas. I randomly use
t0=10 and
t1=40 to indicate that the 30-day time period starts from the 10th day until the 40th day.
Similar to the previous charts, I plot the data and save the chart as DailyReturns.png. The graph should look like this
One way to visually check whether two stocks are correlated is to scatter plot the returns as follows
The chart is saved as ScatterPlot.png, and should look like this
These are four basic plots, which will hopefully give you a better idea of price trends, returns, and relationships between assets.
Inputs: symbols_list, dt_start, dt_end, t0, t1
Outputs: AdjustedClose.png, NormalizedClose.png, DailyReturns.png, ScatterPlot.png
Libraries: Requires pandas_datareader to be installed. In terminal paste “pip install pandas-datareader”
PricePlot.py uses the following dependencies or libraries.
1 2 3 4 5 6 |
import numpy as np import pandas as pd import datetime as dt import matplotlib import matplotlib.pyplot as plt from pandas_datareader.data import DataReader |
Define a function called PricePlot() as well as which stocks you want to analyse and over what time period. The variable symbols_list is a list of the stock tickers you want to examine. Note that the tickers you add in the list should be the same tickers used by Yahoo Finance, since this script retrieves data from there. So make sure you have the correct ticker name. For this exercise, I use four stocks ( AA: Alcoa Inc, AAPL: Apple Inc, MCD: McDonald’s Corporation, and YHOO: Yahoo! Inc.) Add the start and end dates for your study. The datetime library transforms your input into a date format.
8 9 10 11 12 13 14 15 16 |
def PricePlot(): ## Define what you want to study and over what period # List of symbols symbols_list = ['AA', 'AAPL', 'MCD', 'YHOO'] # Start and End dates dt_start = dt.datetime(2012, 1,1) dt_end = dt.datetime(2015, 1,1) |
Next, I use the Yahoo Finance downloader provided by Pandas to download historical prices of all stock tickers in the list symbols_list. Note that I indicate that I want adjusted closing prices using ['Adj Close'] since the DataReader downloads other information as well including Open, Close, High, Low and Volume for each stock.
18 19 |
# Download historical Adjusted Closing prices using Pandas downloader for Yahoo: pandas.io.data.DataReader data = DataReader(symbols_list, 'yahoo', dt_start, dt_end)['Adj Close'] |
Once the time-series of prices are downloaded, we start by plotting the adjusted closing prices of all four stocks on the same graph in order to visualise price trends.
20 21 22 23 24 25 26 27 |
# Plotting Adj Closing prices with x-axis = time. Saves chart as png in directory. plt.clf() plt.plot(data) plt.legend(symbols_list) plt.ylabel('Adjusted Close') plt.xlabel('Date') matplotlib.rcParams.update({'font.size': 8}) plt.savefig('AdjustedClose.png', format='png') |
The resulting chart is saved as AdjustedClose.png and should look like this

28 29 30 31 32 33 34 35 36 |
# Normalizing prices to start at 1 to visualize relative value over time. data_normalized = data/data.iloc[0] plt.clf() plt.plot(data_normalized) plt.legend(symbols_list) plt.ylabel('Normalized Close') plt.xlabel('Date') matplotlib.rcParams.update({'font.size': 8}) plt.savefig('NormalizedClose.png', format='png') |
Similar to the previous chart, I plot the relative prices and obtain a chart that looks like this

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# Plotting returns over 30 days starting after t0=10 days and ending at t1=40 # First create dataframe data_ret which includes returns data_ret = data/data.shift(1) - 1 t0=10 t1=40 # Plot Daily returns plt.clf() plt.plot(data_ret[t0:t1]) plt.axhline(y=0, color='b') plt.legend(symbols_list) plt.ylabel('Daily Returns') plt.xlabel('Date') matplotlib.rcParams.update({'font.size': 8}) plt.savefig('DailyReturns.png', format='png') |
Similar to the previous charts, I plot the data and save the chart as DailyReturns.png. The graph should look like this

52 53 54 55 56 57 58 59 60 |
# Scatter plot of two stocks AA and AAPL plt.clf() plt.scatter(data_ret['AA'], data_ret['AAPL'], c='green') plt.xlabel('AA') plt.ylabel('AAPL') matplotlib.rcParams.update({'font.size': 8}) plt.savefig('ScatterPlot.png', format='png') PricePlot() # Don't forget to call the function |
The chart is saved as ScatterPlot.png, and should look like this
