Discover more from All About Trading!
Smart Stock Fundamental Analysis in Python
Using Python to Fetch Key Fundamental Data from FMP
Quality data plays a crucial role in stock analysis due to its direct impact on the accuracy and reliability of the insights and conclusions drawn from the analysis. This article shows how to import financial metrics and shows a way to sort them through a graph.
Quick Introduction to FMP
Financial Modeling Prep (FMP) API provides real time stock price, company financial statements, major index prices, stock historical data, forex real time rate and cryptocurrencies. FMP stock price API is in real time, the company reports can be found in quarter or annual format, and goes up to 30 years back in history. This article will show one way to use the API to import company fundamentals and sort them.
Fundamental Analysis and Ratios
Stock fundamental analysis is a method used by investors and analysts to evaluate the intrinsic value of a company’s stock based on its underlying financial and economic factors.
The goal of fundamental analysis is to assess the company’s financial health, growth potential, and overall performance to make informed investment decisions. This analysis involves examining various fundamental aspects of the company, such as its financial statements, industry trends, management quality, and competitive position.
Let’s see how to fetch two key valuation metrics using the company’s API.
Importing and Visualizing the PEG Ratio
The PEG ratio, which stands for Price/Earnings to Growth ratio, is a financial metric used to assess the valuation of a company’s stock by taking into account its earnings growth. It’s an extension of the more commonly known Price-to-Earnings (P/E) ratio.
The PEG ratio factors in both the company’s price-to-earnings ratio and its projected earnings growth rate. The formula for calculating the PEG ratio is:
P/E Ratio: Price-to-Earnings ratio, calculated as the stock price divided by the earnings per share (EPS).
Earnings Growth Rate: The expected percentage growth rate of the company’s earnings over a specific period, often one year or five years.
The idea behind the PEG ratio is to provide a more nuanced valuation measure by accounting for the growth potential of a company. A lower PEG ratio is generally considered more attractive because it suggests that the stock might be undervalued relative to its expected growth rate. Conversely, a higher PEG ratio might indicate that the stock is overvalued given its growth prospects.
However, it’s important to note that the PEG ratio has its limitations. It assumes that the relationship between the P/E ratio and the earnings growth rate is linear, which might not always hold true. Additionally, the accuracy of the PEG ratio relies on the accuracy of the projected earnings growth rate, which can be difficult to estimate. As with any financial metric, it’s advisable to consider the PEG ratio in conjunction with other factors when making investment decisions.
You have to create an account and get your API key and replace it in the appropriate place in the previous code. I highly recommend this as it takes no longer than a few minutes.
Let’s take a selection of nine stock giants and sort them according to their PEG ratio:
The code to generate the chart is as follows:
try: # For Python 3.0 and later from urllib.request import urlopen except ImportError: # Fall back to Python 2's urllib2 from urllib2 import urlopen import certifi import json def get_jsonparsed_data(url): response = urlopen(url, cafile=certifi.where()) data = response.read().decode("utf-8") return json.loads(data) AAPL = ('https://financialmodelingprep.com/api/v3/ratios-ttm/AAPL?apikey=YOUR_API_KEY') AMZN = ('https://financialmodelingprep.com/api/v3/ratios-ttm/AMZN?apikey=YOUR_API_KEY') NVDA = ('https://financialmodelingprep.com/api/v3/ratios-ttm/NVDA?apikey=YOUR_API_KEY') GOOGL = ('https://financialmodelingprep.com/api/v3/ratios-ttm/GOOGL?apikey=YOUR_API_KEY') META = ('https://financialmodelingprep.com/api/v3/ratios-ttm/META?apikey=YOUR_API_KEY') TSLA = ('https://financialmodelingprep.com/api/v3/ratios-ttm/TSLA?apikey=YOUR_API_KEY') PG = ('https://financialmodelingprep.com/api/v3/ratios-ttm/PG?apikey=YOUR_API_KEY') ABBV = ('https://financialmodelingprep.com/api/v3/ratios-ttm/ABBV?apikey=YOUR_API_KEY') PEP = ('https://financialmodelingprep.com/api/v3/ratios-ttm/PEP?apikey=YOUR_API_KEY') AAPL_metric = get_jsonparsed_data(AAPL)['priceEarningsToGrowthRatioTTM'] AMZN_metric = get_jsonparsed_data(AMZN)['priceEarningsToGrowthRatioTTM'] NVDA_metric = get_jsonparsed_data(NVDA)['priceEarningsToGrowthRatioTTM'] GOOGL_metric = get_jsonparsed_data(GOOGL)['priceEarningsToGrowthRatioTTM'] META_metric = get_jsonparsed_data(META)['priceEarningsToGrowthRatioTTM'] TSLA_metric = get_jsonparsed_data(TSLA)['priceEarningsToGrowthRatioTTM'] PG_metric = get_jsonparsed_data(PG)['priceEarningsToGrowthRatioTTM'] ABBV_metric = get_jsonparsed_data(ABBV)['priceEarningsToGrowthRatioTTM'] PEP_metric = get_jsonparsed_data(PEP)['priceEarningsToGrowthRatioTTM'] categories = ['AAPL', 'AMZN', 'NVDA', 'GOOGL', 'META', 'TSLA', 'PG', 'ABBV', 'PEP'] values = [AAPL_metric, AMZN_metric, NVDA_metric, GOOGL_metric, META_metric, TSLA_metric, PG_metric, ABBV_metric, PEP_metric] colors = ['blue' if value > 0 else 'green' for value in values] # Sort the data based on values sorted_data = sorted(zip(categories, values, colors), key=lambda x: x) # Extract sorted categories, values, and colors sorted_categories, sorted_values, sorted_colors = zip(*sorted_data) # Create the bar plot import matplotlib.pyplot as plt plt.bar(sorted_categories, sorted_values, color=sorted_colors) # Adding labels and title plt.ylabel('PEG Ratio') # Display the plot plt.show() plt.axhline(y = 0, color = 'black')
Importing and Visualizing the ROE
Return on Equity (ROE) is a financial ratio that measures a company’s profitability and efficiency in generating profits using its shareholders’ equity. It shows how much profit a company generates in relation to the equity invested by its shareholders. ROE is often used by investors and analysts to assess a company’s financial performance and its ability to generate returns for its shareholders.
The formula to calculate Return on Equity (ROE) is:
Net Income: The company’s net profit after deducting all expenses, taxes, and interest.
Shareholders’ Equity: Also known as book value, it represents the total value of assets minus liabilities. It’s the residual interest in the company’s assets after all debts are paid off.
ROE represents the percentage of net income generated for each dollar of shareholders’ equity. A higher ROE is generally considered more favorable, as it suggests that the company is efficiently using its equity to generate profits.
It’s important to note that the interpretation of ROE varies by industry and company size. Different industries have different typical levels of profitability, and larger companies might have lower ROE values due to their scale. Comparing a company’s ROE to its peers or industry averages can provide a more meaningful assessment of its performance.
ROE can also be broken down further using the DuPont analysis, which decomposes ROE into three components: net profit margin, asset turnover, and financial leverage. This breakdown provides insights into the company’s profitability, efficiency in utilizing assets, and financial structure. While ROE is a valuable metric, it’s best used in conjunction with other financial ratios and qualitative factors to gain a comprehensive understanding of a company’s financial health and prospects.
Let’s take the same stocks and sort them according to their ROE ratio:
The code to generate the chart is as follows:
AAPL_metric = get_jsonparsed_data(AAPL)['returnOnEquityTTM'] AMZN_metric = get_jsonparsed_data(AMZN)['returnOnEquityTTM'] NVDA_metric = get_jsonparsed_data(NVDA)['returnOnEquityTTM'] GOOGL_metric = get_jsonparsed_data(GOOGL)['returnOnEquityTTM'] META_metric = get_jsonparsed_data(META)['returnOnEquityTTM'] TSLA_metric = get_jsonparsed_data(TSLA)['returnOnEquityTTM'] PG_metric = get_jsonparsed_data(PG)['returnOnEquityTTM'] ABBV_metric = get_jsonparsed_data(ABBV)['returnOnEquityTTM'] PEP_metric = get_jsonparsed_data(PEP)['returnOnEquityTTM'] colors = ['blue' if value > 0 else 'green' for value in values] # Sort the data based on values sorted_data = sorted(zip(categories, values, colors), key=lambda x: x) # Extract sorted categories, values, and colors sorted_categories, sorted_values, sorted_colors = zip(*sorted_data) # Create the bar plot plt.bar(sorted_categories, sorted_values, color=sorted_colors) # Adding labels and title plt.ylabel('Return on Equity') # Display the plot plt.show() plt.axhline(y = 0, color = 'black')
You can try this out with more companies. Here’s an excerpt of a few tickers you may use:
It’s may be worth sorting them out and composing a portfolio with the best valuation metrics such as a low PEG ratio.
Here’s another excerpt of the possible metrics that you may fetch from the data:
Quality of Data
Judging the quality of data from a data provider is crucial for making informed decisions and conducting accurate analyses. Here are some steps you can take to evaluate the quality of data from a data provider. Check for accuracy by comparing the data from the provider to other reliable sources or real-world observations. Look for inconsistencies or errors in the data. Ensure that the data covers all the relevant variables and time periods you need.
Incomplete data might lead to biased or inaccurate analysis. Verify if the data is consistent over time and across different datasets. Inconsistent data might raise concerns about the data provider’s processes. Assess how frequently the data is updated. Timely data is essential for making current decisions and tracking changes accurately.
Look for thorough documentation that explains the data’s structure, variables, units, and any transformations applied. This documentation helps you interpret the data accurately. And finally, Research the data provider’s reputation in the industry. Read reviews and testimonials, and check if they offer reliable customer support. In my experience so far, FMP passes all these tests and adds value with regards to fundamental and even technical research.
Are you interested in market sentiment and its strength to deliver powerful market forecasts? If so, then you can check out my other newsletter The Weekly Market Sentiment Report. It’s a weekly newsletter that highlights and explains the key market configurations using powerful market sentiment indicators and strategies!