avatarFarhad Malik

Summary

The provided content outlines a methodical approach to automating stock market fundamental analysis using Python, detailing key financial ratios and indicators to assess a company's investment potential.

Abstract

The article delves into the concept of fundamental analysis for stock market investment, emphasizing the importance of evaluating a company's financial health before making investment decisions. It explains various fundamental analysis ratios, such as market capitalization, price-to-sales (P/S), price-to-earnings (P/E), and price-to-book (P/B) ratios, as well as measures of management effectiveness like return on assets (ROA) and return on equity (ROE). The author also discusses income statement analysis, including profit and operating margins, and balance sheet analysis, including current ratio and debt-to-equity ratio. The article provides Python code to automate the extraction of these fundamental indicators, enabling investors to compute a company's intrinsic value and make more informed investment decisions. The code uses libraries like pandas and yahoo_fin to fetch and process financial data from Yahoo Finance.

Opinions

  • The author suggests that smaller cap stocks are riskier but can yield higher returns compared to large cap stocks, which are generally safer investments.
  • It is the author's view that a lower price-to-sales (P/S) ratio indicates an undervalued company, while a higher ratio suggests it is overvalued.
  • The author believes that a company with a higher PEG ratio is considered more valuable, but when both the PE and PEG ratios are high, it may indicate that the company is overvalued.
  • A price-to-book (PB) ratio lower than 1 is seen as a sign that a company is undervalued, whereas a ratio higher than 1 suggests it is overvalued.
  • The author opines that higher ROA and ROE values reflect more effective management, as they indicate the company's ability to generate income from its assets and equity.
  • The author advises that a current ratio greater than 1 is preferable, indicating a company's ability to pay off short-term debt without additional borrowing.
  • The author's perspective is that a higher payout ratio, especially above 100%, could mean a company is paying out more in dividends than its earnings, which might not be sustainable.
  • The author emphasizes that fundamental analysis is subjective and should be used as a guide rather than a definitive predictor of investment success.

Automating Stock Investing Fundamental Analysis With Python

Explaining Stock Trading Fundamental Analysis Ratios And Retrieving Them Using Python

Passive income can be generated by investing in stock markets. The number of private retail investors has increased recently, probably due to the fact that work from home is a norm nowadays and nearly everyone has access to the internet/news.

Before we invest our money in a company and buy its stock, we need to perform the required due diligence. There is no guarantee that we will make money and some investors lose some if not all, of their investments hence it is wise not to invest in a company that is going to go bust or that is overvalued and its share price is already too high. The share price of overvalued companies tends to decrease over time. Hence, we need a way to measure the company’s fundamentals before we invest our money into the stock market.

This article will explain the concept of fundamental analysis which can help us pick the companies to invest in.

In a nutshell, we are going to understand whether a company is undervalued, fair valued, or overvalued.

If you are new to the world of trading and the stock market then I highly recommend reading this article to familiarise yourself with the basics of the trading fundamentals.

Fundamental analysis is one of the key methodologies to follow to analyze a company. It is performed to get a better understanding of our target companies.

Fundamental analysis uses the information of a company such as its balance sheet, income statements, etc. to compute its value.

Article Aim

  • This article helps us understand what fundamental analysis is and which key indicators we need to measure. Hence, I will start by explaining the concept of fundamental analysis
  • Then I will highlight some of the key measures and how the measures are computed.
  • Finally, I will present the Python code that we can use to automate the fundamental analysis of a company using Python language.

I have added the code snippet near the end.

Note, the fundamental analysis provides us the indicators to gauge our understanding on how suitable a company is for us to invest in. The indicators by nature do not guarantee the returns. They, most of the times, help us in making our decisions better.

Stock Market Fundamental Analysis

Quick Note Worth Mentioning

  1. If we know that a company is healthy, it is investing its income to grow itself and is launching new products, its net income is more than its costs and its management is effective, it does not have any debt and the share price is undervalued then we can feel confident that the value of the company is likely to grow and the company won’t go bankrupt anytime soon.
  2. No one can accurately predict the stock market. The market can be volatile and it can change due to an unlimited number of factors.
  3. I have presented my opinions in this article. This article does not guarantee any positive returns and should be used for educational purposes only. The opinions expressed in the article may change without notice as new information is obtained.
  4. An investor can lose some, if not all, of his/her investments therefore it is important to seek a professional’s advice before investing money in a company.
  5. The stock market cannot always be timed and there is no guarantee that an investor will earn a profit.
  6. The key concept to understand is that each company has its intrinsic value. The fundamental analysis is all about calculating the intrinsic value of the company. This analysis is subjective in nature. There are way too many indicators available and a mix of them can help us value a company.

Let’s start

There are 100s of fundamental indicators. I will explain most of the key indicators I use during my analysis.

1. What Is Fundamental Analysis?

There are thousands of publicly listed companies. We can choose to invest our money in all of them but some of the companies are better for our investment than the others.

There are a large number of methodologies available to analyze and measure the health of a company.

One of the key methodologies is known as fundamental analysis.

Fundamental analysis is when an analyst values a stock of a company by assessing the company-level factors such as the state of its balance sheet, market capitalization, how the management of the company is, and so on.

The fundamental analysis helps us understand what to look for in a company. The result of fundamental analysis is a set of fundamental indicators.

Therefore, the fundamental analysis uses both the intrinsic value of the stock along with the external factors to compute its value.

The more we understand about the company we want to invest in, the higher the chances of us deriving the true value of the company.

There are a large number of fundamental analysis indicators. We will concentrate on a handful of important indicators. I will also illustrate how we can extract the values for a company.

2. What do we want to get out of the fundamental analysis?

Essentially we want to understand whether we should invest in a company and whether buying its shares is the right decision for the short, medium, and long-term.

Each company’s stock has a current stock price. This is the share price value that you see on the exchanges or on the brokerage or finance websites. We can make calculated judgments to increase our chances of gaining profits and one of the ways to measure a company’s health is by looking into its fundamentals and computing the required indicators.

As an instance, we usually observe share price of a company if we search for a company in Yahoo finance. The share price changes on a periodic basis due to a large number of reasons; one of them being supply and demand of the stocks.

The question is whether the current share price is below or above the intrinsic value. The fundamental analysis can help us understand the companies better.

Sometimes, the hardest part is to decide on the important investment aspects of a company.

I will concentrate on the key fundamental key indicators. However, it does not mean that we should ignore others.

3. Basic Understanding

The fundamental analysis should help us understand the following key questions:

  1. What is the market capitalization of a company? Is the company growing and earning profits?
  2. Is my target company under debt? What is their debt-to-equity ratio?
  3. Is the company undervalued or overvalued in terms of its market and book value, sales, earnings, and profits?
  4. What is their price per earnings and price per earnings growth ratios?
  5. What are the returns on assets and equities? What is the dividend payout ratio?

There are a large number of useful fundamental indicators such as dividend yield, EPS, and so on. I want to concentrate on the most common measures I use.

Let’s understand the measures and compute them in Python for any company for us.

I have divided the fundamental measures into different sections.

Please note, I have mentioned my opinion on how each indicator can guide us however they are not applicable in all scenarios and should not be taken as absolute rules.

This article is for educational purposes only.

4. Valuation measures

4.1 Market Capitalization:

  • Let’s start by understanding what market capitalization is. Market capitalization is also known as market cap. The market cap is one of the measures to determine the size of a company. We can use the market cap measure to categorize a company into a large, medium, or small-sized company category.
  • The market capital figure informs us about the market value of a company which is simply the product of outstanding shares and the current price of one share. Therefore, we can use the market cap figure to estimate how valuable the company is to the market.
  • Usually, large-cap companies have a market cap greater than $10Billion, the medium is anywhere from $2B to $10B and the small-cap is anywhere below $2B.
  • We can further break the cap down into more categories if needed. Generally, it’s wise to diversify the portfolio and add a mix of large, medium, and small-cap companies’ stocks in the portfolio.

Author’s Opinion: The smaller cap stocks are generally riskier and are more volatile than the large market cap companies. The large-cap companies yield fewer returns than the small-cap companies but they are generally safer investments.

4.2 PS Ratio

  • The P/S ratio, which is also known as the Price To Sales Ratio, is used to inform about how much the market capitalization exceeds the sales of a company. Typically, past 12 months sales are used.
  • It is essentially the ratio of market capitalization to the sales of a company. Therefore, the ratio can help us understand how much the other investors are paying for one dollar of sales of stock.
  • The ratio is computed by dividing the market capitalization of the share by the total sales of a company. Therefore, as the number of outstanding shares or the share price of a company increases, the ratio increases. If the sales of a company decrease then the ratio increases.

Author’s Opinion: The key point to take is that if the ratio is lower than 1 then the company is undervalued and if the ratio is greater than 1 then the company is overvalued. Generally, the higher the value, the more the stock is valued by the investors.

4.3 PE Ratio

  • The Price to Earnings ratio is one of the most used ratios within the fundamental analysis measures. It can help us determine whether the company is over or undervalued with respect to other companies within the industry.
  • There are multiple ways to calculate the ratio. We can either take the market capitalization and divide it by the earnings or we can take the current share price and divide by the Earnings Per Share (EPS). The earnings per share inform us how much the company makes per share. It is merely the total earnings of a company divided by the outstanding shares. If the EPS is positive then the company is profitable. Therefore it makes more than it costs.
  • PE ratio is the Trailing Price To Earning ratio. The word trailing here refers to the earnings of the last 12 months. Essentially, we take the market capitalization and divide it by the actual last 12 month’s earnings per share. We can use the PE ratios to compare similar companies within an industry and to determine whether the company stock price is over or undervalued.
  • A company with a higher PE ratio usually has a higher earnings growth rate.

Author’s Opinion: The key point to take is that PE needs to be compared with the companies within the same industry. The higher the value, the more the company is valued.

4.5 PEG ratio

  • The PEG ratio is also known as the Price To Earnings Ratio Over Earnings Growth Rate. This is computed by calculating the PE ratio and dividing by the earnings growth. We can use the annual earnings growth rate.
  • We can use the PEG ratio to compute the true value of a stock. The lower the PEG ratio, the undervalue the stock is. The PEG ratio can help us understand how fast a company can grow.
  • The higher the PEG ratio, the more the company is valued, therefore the lower the value, the undervalue the company is. When both the PE and PEG ratios are high then they are good indicators that the company is overvalued.

4.6 PB Ratio = Price/Book Ratio

  • The price to book ratio is computed by taking the market capitalization and dividing it by the book value of the company. We can also compute it by taking the current share price and dividing it by the book value per share.
  • The book value is the difference between the assets and liabilities. Imagine if all of the assets of a company are liquidated to pay all of the liabilities then whatever we are left with is known as book value. The market value on the other hand is the price that the market values the company as.

Author’s Opinion: The key point to take is that if the ratio is lower than 1 then the company is undervalued and if the ratio is higher than 1 then it is overvalued. The higher the value, the more the company is valued. We should ensure that the book value and market value of a company are positive. Generally, the lower the ratio, the better the investment.

5. Management Effectiveness

5.1 ROA

  • Each company has its assets, liabilities, and annual net income that it generates from the assets. The ROA stands for Return On Assets.
  • The ROA measure informs us about the income the company can generate from its assets.
  • Therefore if a company has effective management then it will be reflected in the ROA.

Author’s Opinion: The higher the ROA value, the more effective the management of a company because the more the company can possibly generate more net income from its assets.

5.2 ROE

  • The ROE stands for Return On Equity.
  • Remember that shareholder equity, or commonly known as equity, is the difference between the assets and the liabilities of a company.
  • It is calculated by dividing the net income by the shareholder equity.
  • This is again an indicator of how efficient the management of a company is. It informs us about the returns of a company in relation to the equity held by its stockholders.

Author’s Opinion: The higher the value, the better the company in generating returns.

6. Income Statement

6.1 Profit Margin

  • Profit margin is an important measure as it helps us understand the degree to which the company is generating income over its revenue. It is the ratio of the net income of a company over its revenue.
  • Therefore, if a company generates less income than its revenue then it will have a lower profit margin. It is a measure of a company’s efficiency.
  • These figures are available in the income statement of a company.

Author’s Opinion: A company that generates a higher profit margin generates higher income when compared to its expenses and therefore is considered a healthier company.

6.2 Operating Margin

  • The operating margin is another measure of profit.
  • It is calculated by dividing the operating profit by the sales revenue. The profit is computed by calculating the difference between the revenue and all of the costs of a company.
  • These figures are available in the income statement of a company.

Author’s Opinion: We might be able to conclude that the higher the operating margin, the profitable the company with lower costs.

7. Balance Sheet & Dividends

7.1 Current Ratio

  • The current ratio is one of the important balance sheet ratios to consider. It is a liquidity ratio and can inform us about the health of a company. It indicates whether the company can pay off its short-term debt.
  • It is calculated by dividing the current assets over the current liabilities.
  • The key to remember is that the higher the current ratio, the better the company can be considered for investment.
  • It is a good indication to invest in a company that has higher assets than its liabilities.

Author’s Opinion: Ideally, the current ratio should be greater than 1 indicating that it can pay-off its liabilities without borrowing the money.

7.2 Cash Per Share

  • This is the available cash over the number of outstanding shares.

Author’s Opinion: The more cash there is in a company, the more the business can spend on itself and make positive changes for the shareholders by growing the company or its products as an instance.

7.3 D/S Ratio = Total Debt/Equity Ratio

  • This measure is calculated by taking the ratio of liabilities of a company by the equity of the company.
  • Remember the equity of a company is the difference between its assets and liabilities. Therefore, a positive number is considered healthier.

Author’s Opinion: Companies that have a higher debt ratio can potentially default on their debt therefore it’s wise to choose a company with lower debt to equity ratio and ensuring that it is a positive number.

7.4 Payout Ratio

  • The payout ratio is directly related to the dividends that the company pays to its shareholders. Some of the most established companies pay a percentage of their earnings to their shareholders.
  • The payout ratio is calculated by dividing the dividend amount per share by the earnings per share.
  • Some companies do not pay dividends whereas some companies invest a large portion of their income back into their business. When the payout ratio is low then it could mean that the company is investing back into its business. This again could imply, that the company is expanding.

Author’s Opinion: When the payout ratio is high (higher than 100) then it means the company is paying more in dividends than its earnings.

8. Code

Firstly, create a file named: fundamental_indicators_provider.py

Add the helper code:

class Company:
   def __init__(self, symbol):
      self.symbol = symbol
      self.fundamental_indicators = {}
def to_float(val):
    if val == 0:
        return float(0)

    val = str(val).upper()
    
    if '%' in val:
        return round(float(val[:-1]), 4)

    m = {'K': 3, 'M': 6, 'B': 9, 'T': 12}

    for key in m.keys():
        if key in val:
            multiplier = m.get(val[-1])
            return round(float(val[:-1]) * (10 ** multiplier), 4)
    return round(float(val), 4)
def get_statatistics(symbol):
    url = f"https://finance.yahoo.com/quote/{symbol}/key-statistics?p={symbol}"
    dataframes = pandas.read_html(url)
    return pandas.concat(dataframes[1:])
def get_data_item(result, dataframe, columns):
    for column_to_find, column_to_name in columns.items():
        try:
            result[column_to_name] = list((dataframe.loc[dataframe[0] == column_to_find].to_dict()[1]).values())[0]
        except Exception as ex:
            result[column_to_name] = 'NA'

def get_last_data_item(result, dataframe, columns):
    data = dataframe.iloc[:, :2]
    data.columns = ["Column", "Last"]

    for column_to_find, column_to_name in columns.items():
        try:
            val = data[data.Column.str.contains(column_to_find, case=False, regex=True)].iloc[0, 1]
            float_val = to_float(val)
            result[column_to_name] = float_val
        except Exception as ex:
            result[column_to_name] = "NA"

Then the main function that populates the fundamental indicators

import asyncio
import pandas
import yahoo_fin.stock_info as si
async def get_fundamental_indicators_for_company(config, company):
    company.fundmantal_indicators = {}

 # Statistics Valuation
 keys = {
    'Market Cap (intraday) 5': 'MarketCap',
    'Price/Sales (ttm)': 'PS',
    'Trailing P/E': 'PE',
    'PEG Ratio (5 yr expected) 1': 'PEG',
    'Price/Book (mrq)': 'PB'
 }
 data = si.get_stats_valuation(company.symbol)
 get_data_item(company.fundmantal_indicators, data, keys)

 # Income statement and Balance sheet
 data = get_statatistics(company.symbol)

 get_data_item(company.fundmantal_indicators, data,
              {
                  'Profit Margin': 'ProfitMargin',
                  'Operating Margin (ttm)': 'OperMargin',
                  'Current Ratio (mrq)': 'CurrentRatio',
                  'Payout Ratio 4': 'DivPayoutRatio'
              })

 get_last_data_item(company.fundmantal_indicators, data,
           {
               'Return on assets': 'ROA',
               'Return on equity': 'ROE',
               'Total cash per share': 'Cash/Share',
               'Book value per share': 'Book/Share',
               'Total debt/equity': 'Debt/Equity'
           })

9. Let’s run it

Create a new file: runner.py

Add the following lines of code

import fundamental_indicators_provider
config = {}
company = Company('ROKU')
# Note: 
You might want to create an event loop and run within the loop:
loop = asyncio.get_event_loop()
loop.run_until_complete(fundamental_indicators_provider.get_fundamental_indicators_for_company(config, company))
print(company.fundmantal_indicators)

10. Result

MarketCap       53.67B
PS              34.86
PE              nan
PEG             18.90
PB              44.11
ProfitMargin    -6.53%
OperMargin      -6.42%
CurrentRatio    3.29
DivPayoutRatio  0.00%
ROA             -4.12
ROE             -11.97
Cash/Share      8.25
Book/Share      9.59
Debt/Equity     36.1

11. Summary

We understood that fundamental analysis is when an analyst values a stock of a company by assessing the company level factors such as the state of its balance sheet, market capitalization, how the management of the company is, and so on.

This article presented a handful of important fundamental measures to consider when investing in a company. The indicators only help us increase our confidence and increase the possibility of investing in a healthier company. I always suggest seeking the advice of professional investors before investing.

It’s worth noting that the fundamental analysis helps us compute the intrinsic value of a company. Therefore, if the computed intrinsic value is below the current stock price then we can conclude that the company’s stock price is overvalued and if the current intrinsic value is above the stock price then we can consider it to be undervalued.

The healthier companies can overcome financial difficulties and those might be good investment candidates.

Finance
Trading
Python
Fintech
Programming
Recommended from ReadMedium