Mastering Stock Fundamental Analysis with Python Tools
Written on
Chapter 1: Understanding Fundamental Analysis
Fundamental analysis is a method used to evaluate a company's financial performance to determine investment potential. Companies with robust fundamentals are more likely to experience growth, thereby creating wealth for investors. Hence, understanding these fundamentals is crucial. Financial data is publicly available through various reports such as balance sheets, income statements, cash flow statements, and annual reports, which provide the necessary information for analysis. However, a background in finance is beneficial for interpreting these documents effectively.
To simplify the process, several financial ratios serve as indicators of a company's health, and these ratios can be accessed through numerous websites and APIs, some of which are free. For our analysis, we will utilize a free service from Yahoo Finance to retrieve the required data.
In this article, we will discuss the following topics:
- Key fundamental ratios
- Retrieving these ratios using Python
- Applying these ratios in stock analysis
Section 1.1: Key Fundamental Ratios
We will delve into four widely used ratios that form the basis of financial analysis:
- Price to Earnings Ratio (P/E): This ratio compares a company's share price to its earnings per share (EPS). A high P/E ratio may indicate overvaluation, whereas a low ratio suggests undervaluation. However, it's important to consider other valuation factors alongside the P/E ratio. Typically, a P/E ratio over 30 is regarded as high.
- Formula: P/E = Stock Price / Earnings per Share (EPS)
- Price to Book Ratio (P/B): This ratio assesses the relationship between a company's stock price and its book value. A lower P/B ratio signals an undervalued stock. For instance, if a company's book value is 50 and its stock price is 500, the P/B ratio is 10.
- Formula: P/B = Stock Price / Book Value
- Price to Sales Ratio (P/S): This straightforward ratio helps investors understand what they are paying for the company's sales. A lower P/S ratio indicates undervaluation, while a higher ratio suggests overvaluation.
- Formula: P/S = Stock Price / Sales per Share
- Price-Earnings to Growth Ratio (PEG): An enhanced version of the P/E ratio, the PEG ratio incorporates expected growth, providing a more comprehensive view. A PEG ratio below 1 is indicative of an undervalued stock.
- Formula: PEG = P/E / EPS Growth
Section 1.2: Loading Required Libraries
To access the fundamental data for various stocks, we will utilize Yahoo Finance. Here’s how to set up your environment:
import pandas as pd
import numpy as np
import yahoo_fin.stock_info as si
import pandas as pd
Configuring Your Data Range
We will analyze data from February 2022 to February 2023:
start_date = '2022-02-02'
end_date = '2023-02-02'
tickers = ['AAPL', 'IBM', 'MSFT', 'WMT', 'AMGN', 'AXP', 'BA',
'NKE', 'PG', 'TRV', 'UNH', 'V', 'VZ', 'WBA', 'WMT']
ratio_stat = ['Trailing P/E', 'Forward P/E', 'PEG Ratio (5 yr expected)',
'Price/Book (mrq)', 'Price/Sales (ttm)',
'Enterprise Value/EBITDA', 'Enterprise Value/Revenue']
Retrieving Data from Yahoo Finance
The following function allows us to download the necessary data for the selected stocks:
def load_data(self):
try:
data = pd.DataFrame(columns=self.tickers)
for ticker in self.tickers:
data[ticker] = yf.download(self.ticker,
self.start_date,
self.end_date)['Adj Close']
return data
except Exception as e:
print(f'An exception occurred while executing load_data: {e}')
Fetching Fundamental Data
We will utilize the get_stats_valuation function to collect the required data and construct a DataFrame with the ratios for all companies:
def get_fundamental(self):
try:
df_fundamentals = pd.DataFrame()
for ticker in range(len(self.tickers)):
stock_name = str(self.tickers[ticker])
fundamental_ratio = si.get_stats_valuation(stock_name)
fundamental_ratio.index = fundamental_ratio[0]
fundamental_ratio = fundamental_ratio.drop(labels=0, axis=1)
tmp_table = fundamental_ratio.T
tmp_table = tmp_table[self.ratio_stat]
df_fundamentals = df_fundamentals.append(tmp_table)
df_fundamentals.index = self.tickers
df_fundamentals = df_fundamentals.astype('float')
df_fundamentals.dropna(inplace=True)
return df_fundamentals
except Exception as e:
print(f'An exception occurred while executing get_fundamental: {e}')
Practical Applications of Ratios
These ratios can help identify stocks that are either overvalued or undervalued. For a basic analysis, we can use a simple ratio called over_under:
over_under = P/E of a specific stock / mean P/E of all the stocks
- If over_under > 1, the stock is overvalued.
- If over_under < 1, the stock is undervalued.
- If over_under = 1, it is fairly valued.
The denominator typically represents the industry average P/E. To keep it straightforward, we will calculate the mean of the stocks within our DataFrame:
def get_over_under_stocks(self):
try:
df_fundamentals = self.get_fundamental()
df_fundamentals['Trailing P/E'].mean()
df_fundamentals['over_under'] = (df_fundamentals['Trailing P/E']) / (df_fundamentals['Trailing P/E'].mean())
category = []
for i in df_fundamentals['over_under']:
if i < 1: category.append('Under Valued')
elif i > 1: category.append('Over Valued')
else: category.append('Fair Valued')
df_fundamentals['Category'] = category
return df_fundamentalsexcept Exception as e:
print(f'An exception occurred while executing get_over_under_stocks: {e}')
Closing Thoughts
Fundamental analysis relies on actual data, and when conducted effectively, it can guide sound investment choices. The integration of technology and automation allows for swift analyses using reliable figures. It is crucial to remember that these ratios fluctuate over time and must be recalculated accordingly. They should be regarded as supportive tools rather than standalone indicators for decision-making.
For further reading, I recommend my previous articles on Risk Management of Stocks Using Python and How to Build a Financial Portfolio Using Python, where I delve into return calculations and Value at Risk (VaR) methodologies, along with constructing an optimized financial portfolio.
I hope you found this article insightful and beneficial.
You can connect with me on LinkedIn and GitHub.
Disclaimer
This blog serves educational purposes only and should not be construed as professional financial advice.
References
- Investopedia
- Unsplash
Subscribe to DDIntel Here.
DDIntel aggregates notable insights from our main site and our popular DDI Medium publication. Explore more of our community's insightful work.
Join AItoolverse (alpha) to receive 50 DDINs.
Follow us on LinkedIn, Twitter, YouTube, and Facebook.
This video provides a comprehensive overview of fundamental analysis of stocks using Python, guiding viewers through the basic principles and methodologies.
This introductory video explains financial statement analysis using Python, laying the groundwork for understanding stock evaluation.