Stock Price Trend Analysis – Python for Finance

During this article, we are going to build a very powerful Python tool to perform Stock Price Trend Analysis. Once the script is ready, Python will generate for us below graph showing the price trend from different stocks over time.

Python Plot Stock Prices Trend
Python Plot Stock Prices Trend

This cool Python for Financial Analysis script will take as an input a list of stocks and then it will:

  • Download daily stock prices from recent years for each of the desired companies.
  • Merge all stock prices into a single Pandas DataFrame.
  • Show results as a percentage of the base date (i.e. first day from which we have data).
  • Plot the stock price trend for each of the companies using Matplotlib.

Setting up our Python for Finance Script

In order to start building our Stock Price Trend Analysis script, we need to import a few packages.

First, we will make http requests to a free Financial API where we will get stock daily prices. Then, we will use Pandas to consolidate the API returned financials and merge them into a single Pandas DataFrame. Last, we will use matplotlib to convert our data into a graph.

After importing all required packages, we will have a list of stock tickers for each of the companies that we want to retrieve prices for. As an idea, you could also get, using Python, a list of tickets of all companies in the S&P 500 index and use it as a base for your analysis instead of entering the tickers manually. You can find out how in one of my other articles.

import requests
import pandas as pd
import matplotlib.pyplot as plt

#Enter the ticker of the companies that you want to analyse
companies = ['AAPL','FB','GOOG','F','TSLA']
#empty list to add each of the companies
listofdf = []

Now that we have the initial setup, we can move to the fun part. Our intial goal is to send an http request to the API end point to download daily stock prices.

#API end point request
requests.get(f"https://financialmodelingprep.com/api/v3/historical-price-full/aapl?serietype=line")

#outcome
{
"symbol": "AAPL",
"historical": [
{
"date": "1989-09-19",
"close": 1.54
},
{
"date": "1989-09-20",
"close": 1.59
},
{
"date": "1989-09-21",
"close": 1.6
},

As you can see above in the url, we pass aapl as a parameter (i.e. in the example above is aapl is the ticker for Apple. This parameter indicates to the API for which stock we are requesting stock prices data. Therefore, by changing the url parameter appl to any other company ticker, we will get prices for other companies.

By looking into the response, we see that each of the elements in the list is a dictionary containing the stock price for a day.

for item in companies:
    histprices = requests.get(f"https://financialmodelingprep.com/api/v3/historical-price-full/{item}?serietype=line")
#convert response to json
    histprices = histprices.json()

#Parse the API response and select only last 600 days of prices
    histprices = histprices['historical'][-600:]

#Convert from dict to pandas datafram
    histpricesdf = pd.DataFrame.from_dict(histprices)

#rename column from close to the name of the company
    histpricesdf = histpricesdf.rename({'close': item}, axis=1)
    
#append all dfs to list
    listofdf.append(histpricesdf)

A For loop will let us iterate through each of the companies that we have in our companies list. That way, in each loop iteration we will make a new http request for each of the companies included in the companies list.

Note that we pass as a parameter of the url the word item which represents the stock ticker and will change with each loop iteration.

Then, we slice the Pandas DataFrame to keep only the latest 600 days. Finally, we can use pd.DataFrame.from_dict() to convert our dictionary with the stock prices and dates into a Pandas DataFrame.

Now we have a list call listofdf. Each of the element in the list contains a Pandas DataFrame for each of the stocks. However, having all our stocks in separate Pandas DataFrames is not very helpful for our analysis. Therefore, we are going to merge them into one using the Pandas class method pd.concat.

#set index of each DataFrame by common column before concatinatinghtem
dfs = [df.set_index('date') for df in listofdf]

histpriceconcat = pd.concat(dfs,axis=1)

Great, now we have all stock prices merged in a single Pandas DataFrame:

Python for Finance - Stock Prices
Python for Finance – Stock Prices

As the last step before starting plotting the price trend for each of the stocks, we will divide each of the rows in the DataFrame by the first row. This will enable comparison across stocks since all stock prices will be shown as a percentage difference over time.

Python retrieving Stock prices
Prices over time

A value lower than 1 indicates that the stock price has declined compared to the base date (i.e. 2017-10-04). A value higher than 1 indicates that the price has gone up.

Stock Price Trend Analysis
Photo by Austin Distel on Unsplash

Plotting Stock Price Trends

Our script is almost ready, the only part pending is the Python graph showing the stock price trend over time. We can easily achieve this using matplotlib.

First, we will loop through each of our concatenated Pandas DataFrame in order to plot each of the columns. Then, we can change a bit the layout of the graph by adding a title, rotating the sticks and displaying a legend:

for i, col in enumerate(histpriceconcat.columns):
    histpriceconcat[col].plot()

plt.title('Price Evolution Comparison')

plt.xticks(rotation=70)
plt.legend(histpriceconcat.columns)

#Saving the graph into a JPG file
plt.savefig('foo1.png', bbox_inches='tight')
Matplotlib stock prices trend
Matplotlib – Stock prices trend

Wrapping up

And just like that we have built a nice Python script to perform a Stock Price Trend Analysis. Since prices are shown as a percentage of the first data point, the graph is specially useful to compare price trends from different companies. For example, we can see that Tesla has experience a massive growth in the last few weeks while Apple stock price has been increasing steadily since 2017.

Feel free to play around changing the number of days to plot and the number of companies. For your convinience, see below the whole script.

Enjoy it!

import requests
import pandas as pd
import matplotlib.pyplot as plt



companies = ['AAPL','FB','GOOG','F','TSLA']
listofdf = []
for item in companies:
    histprices = requests.get(f"https://financialmodelingprep.com/api/v3/historical-price-full/{item}?serietype=line")
    histprices = histprices.json()

#Parse the API response and select only last 600 days of prices
    histprices = histprices['historical'][-600:]

#Convert from dict to pandas datafram

    histpricesdf = pd.DataFrame.from_dict(histprices)

#rename column
    histpricesdf = histpricesdf.rename({'close': item}, axis=1)
    
#append all dfs to list
    listofdf.append(histpricesdf)

#set index of each DataFrame by common column before concatinatinghtem
dfs = [df.set_index('date') for df in listofdf]

histpriceconcat = pd.concat(dfs,axis=1)

#divide all dataframe by first line of data to enable comparison
histpriceconcat = histpriceconcat/histpriceconcat.iloc[0]



for i, col in enumerate(histpriceconcat.columns):
    histpriceconcat[col].plot()

plt.title('Price Evolution Comparison')

plt.xticks(rotation=70)
plt.legend(histpriceconcat.columns)
plt.savefig('foo1.png', bbox_inches='tight')


2 thoughts on “Stock Price Trend Analysis – Python for Finance

Comments are closed.