PricePlot.py

Description: PricePlot.py downloads price data from Yahoo Finance and generates multiple price and returns plots to help you visualise trends.

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.


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 esocialtrader-PricePlot-AdjustedClose 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 esocialtrader-PricePlot-NormalizedClose 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 esocialtrader-PricePlot-DailyReturns 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 esocialtrader-PricePlot-ScatterPlot These are four basic plots, which will hopefully give you a better idea of price trends, returns, and relationships between assets.