3/5 – Financial Ratio Analysis Using Python

#3 P&L Statement

This is the third part of the series, where we compare companies’ financials and evaluate their health. In this article, we will continue discussing how to utilize the Python programming language and its libraries to study different companies’ profit and loss statements. We will also discuss different ratios used for a company’s financial analysis and understand what these ratios tell us about the particular company.

Recommended: (3/5) Relative Strength Index (RSI): A Powerful Trading Indicator Implemented in Python

Recommended: (4/5) MACD Indicator: Python Implementation and Technical Analysis

Analyzing Key Financial Ratios

In this article, we will discuss the ratios related to the Profit and loss statement, which can tell a lot about the company’s financial health. The ratios we will examine are Gross Profit Margin, Operating Profit margin, and net profit margin.

Gross Profit Margin

Gross Profit Margin
Gross Profit Margin

Gross profit margin is defined as the ratio of Gross profit to Revenue. A higher gross profit margin means higher profitability, and consistently high profit margins indicate good financial health.

Operating Profit Margin

Operating Profit Margin
Operating Profit Margin

Operating Profit Margin is one of the other famous metrics that gives us an idea of the company’s profitability. An increasing operating profit margin indicates that the company has been improving its operations yearly.

Net profit margin

Net Profit Margin Formula
Net Profit Margin Formula

Net profit margin gives the investor an idea of how well the company manages its expenses. This financial metric is also used for comparison across industries, as resource utilization can be mentioned in a ratio.

Python Code to Calculate Financial Ratios

We will plot Apple Company’s gross profit margin in the code below. We have imported Apple as the ticker ‘AAPL’ from its Profit and Loss statement, and the same is plotted as a line graph.

!pip install yfinance matplotlib pandas
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt

# Define the stock ticker
ticker = 'AAPL'

# Fetch the stock's financial data
stock = yf.Ticker(ticker)
income_stmt = stock.financials.T

# Keep only the last five years of data
income_stmt = income_stmt.tail(5)

# Calculate Gross Profit Margin
income_stmt['Gross Profit Margin'] = (income_stmt['Gross Profit'] / income_stmt['Total Revenue']) * 100

# Display the Gross Profit Margin
print("Gross Profit Margin for Apple Inc. (AAPL) over the last five years:")
print(income_stmt['Gross Profit Margin'])

# Plot the Gross Profit Margin
plt.figure(figsize=(10, 6))
plt.plot(income_stmt.index, income_stmt['Gross Profit Margin'], marker='o', linestyle='-', color='b')
plt.title('Gross Profit Margin of Apple Inc. (AAPL) Over the Last Five Years')
plt.xlabel('Year')
plt.ylabel('Gross Profit Margin (%)')
plt.grid(True)
plt.show()

Let us look at the output of the above code.

Gross Profit Margin Output
Gross Profit Margin Output

We can see that Apple’s Gross profit Margin has been increasing steadily over time. It was below 40% in 2020 and above 40% in the subsequent years. This indicates improving profitability and the company’s good financial health. Let us now look at the operating profit margin code.

import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt

# Define the stock ticker
ticker = 'AAPL'

# Fetch the stock's financial data
stock = yf.Ticker(ticker)
income_stmt = stock.financials.T

# Filter data for the last five years
last_five_years = income_stmt.index[:5]

# Calculate the operating profit margin
income_stmt['Operating Profit Margin'] = (income_stmt['Operating Income'] / income_stmt['Total Revenue']) * 100

# Filter the data for the last five years
op_margin_last_five_years = income_stmt.loc[last_five_years, 'Operating Profit Margin']

# Plot the operating profit margin
plt.figure(figsize=(10, 6))
plt.plot(op_margin_last_five_years.index, op_margin_last_five_years.values, marker='o', linestyle='-', color='b')
plt.title('Operating Profit Margin of Apple Inc. (AAPL) - Last Five Years')
plt.xlabel('Year')
plt.ylabel('Operating Profit Margin (%)')
plt.grid(True)
plt.show()

# Print the operating profit margins
print("Operating Profit Margin for Apple Inc. (AAPL) - Last Five Years")
print(op_margin_last_five_years)

We have just made some minor tweaks to the above code and plotted the Operating Profit margin. Let us now look at the output of the above code.

Operating Profit Margin Output
Operating Profit Margin Output

The operating profit margin increased very suddenly from 2020 to 2021, indicating some positive changes in the company’s operations. Thereafter, the graph is approximately a straight line, indicating a steady operating profit of around 30%.

Let us now look at the code for the Net Profit margin. It is a small change from the basic code used in the previous two versions.

import yfinance as yf
import matplotlib.pyplot as plt

# Fetch financial data for Apple (AAPL) from Yahoo Finance
apple = yf.Ticker("AAPL")
income_statement = apple.financials.T

# Calculate net profit margin
net_income = income_statement['Net Income']
total_revenue = income_statement['Total Revenue']
net_profit_margin = (net_income / total_revenue) * 100

# Plot the net profit margin as a line chart
plt.figure(figsize=(10, 6))
net_profit_margin.plot(marker='o', color='b', linestyle='-')
plt.title('Net Profit Margin of Apple Inc. (AAPL)')
plt.xlabel('Year')
plt.ylabel('Net Profit Margin (%)')
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

# Display the net profit margin for the last five years
print("Net Profit Margin of Apple Inc. (AAPL) for the Last Five Years:")
print(net_profit_margin.tail(5))

Let us look into the output of the above code. Essentially, it gives us the exact inference as the Operating profit margin as their graphs are very similar.

Net Profit Margin Output
Net Profit Margin Output

Conclusion

Here you go! Now you know how to deal with and interpret the ratios provided with the company’s Profit and loss statement. In this article, we looked into the Net profit margin, Operating Profit Margin, and Gross profit margin. We also saw their implementation and interpretation in the Python programming language.

Recommended: Step-by-Step Guide to Checking Out a Commit ID with GitPython

Recommended: How to Debug and Fix Segmentation Faults in Python