The Art of Wise Investments Through Fundamental Analysis
Discover how to leverage fundamental analysis for smarter investment decisions by understanding the core financial health of companies.
When it comes to picking stocks, many investors get drawn in by eye-catching charts and technical analysis. But there’s a less flashy, yet equally powerful tool often overlooked — Fundamental Analysis. It’s like learning the ABCs of a company before diving into any major decisions.
Getting Real with Fundamental Analysis
Yes, charts and trends can look impressive, but for long-term gains, understanding a company’s core health is essential. Fundamental Analysis is about digging into a company’s financials to see how it’s really doing — it’s less about stock movement and more about financial fundamentals.
Meet the EODHD Library: Your Backstage Pass to Company Insights
Imagine having special access to a company’s internal details — that’s the EODHD Financial Python Library. It offers valuable financial information on companies, almost like a detailed report card. For anyone conducting fundamental analysis, this information is invaluable.
The Fundamentals API within EODHD allows us to delve into the data necessary for comparing companies’ financial health. In this article, we’ll use the EODHD Library to explore various aspects of fundamental analysis, drawing comparisons between different companies based on financial fundamentals.
Importing the Necessary Packages
Here are the essential Python packages to get started:
!pip install eodhd
from eodhd import APIClient
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
- Pandas: A powerful data analysis tool, ideal for managing and analyzing data.
- Matplotlib: A comprehensive library for creating visualizations in Python.
- Seaborn: A library for producing appealing graphs and charts.
- eodhd: The official Python library for EODHD, making API access more convenient.
With these tools, we’re ready to tap into the power of fundamental analysis, comparing companies and uncovering insights that can support wise investment decisions.
Extracting the Data through Various Functions
The code below defines functions to retrieve different types of fundamental data for a given stock symbol using the EODHD API. Each function targets specific data.
Extracting Fundamentals
The function extract_fundamentals
retrieves all fundamental data for a given company symbol. This endpoint provides comprehensive company data.
api_key = 'YOUR_API_KEY' #Enter your API KEY here
#Making a EODHD Client
client = APIClient(api_key)
def extract_fundamentals(symbol):
# Purpose: Get overall fundamental data for a stock symbol.
raw_df = client.get_fundamentals_data(symbol)
df = pd.DataFrame(raw_df)
return df
Extracting Valuation Data
The function extract_valuation
retrieves valuation-related information for a stock symbol, focusing on key financial ratios.
def extract_valuation(symbol):
# Purpose: Retrieve valuation-related information for a stock symbol.
raw_df = client.get_fundamentals_data(symbol)
df = pd.DataFrame([raw_df['Valuation']])
return df
extract_valuation(‘TSLA’)
If you’re new to these financial terms, here’s a breakdown to help you interpret each column in the output DataFrame effectively:
- Trailing P/E (Price-to-Earnings) Ratio: This metric divides the current stock price by the earnings per share (EPS) over the last 12 months. It indicates how much investors are willing to pay for a company’s past earnings. A high trailing P/E might suggest that investors expect high growth, while a low P/E may indicate the opposite.
- Forward P/E Ratio: Similar to the trailing P/E, but uses projected future earnings instead of historical earnings. This ratio provides insight into the expected future earnings growth of a company, helping investors assess if the stock is overvalued or undervalued based on future prospects.
- Price-to-Sales (P/S) Ratio (TTM — Trailing Twelve Months): This ratio is calculated by dividing the current market price per share by the revenue per share over the past 12 months. It shows how much investors are willing to pay for each dollar of revenue generated by the company. A high P/S ratio suggests that the market values the company’s revenue growth highly.
- Price-to-Book (P/B) Ratio (MRQ — Most Recent Quarter): The P/B ratio compares a company’s current market price to its book value, which is calculated as total assets minus liabilities. This ratio measures how the market values the company relative to its net asset value. A lower P/B could indicate that the stock is undervalued, while a higher P/B suggests the market sees potential growth or competitive advantage.
- Enterprise Value: This figure combines a company’s market capitalization, debt, and cash to represent its total value. Unlike market capitalization alone, enterprise value offers a more comprehensive picture of the company’s worth, accounting for its debt and cash holdings.
- Enterprise Value to Revenue Ratio: Calculated by dividing the enterprise value by the company’s revenue, this ratio provides another perspective on valuation by showing how much the total value of the company (not just its stock) compares to its revenue. A higher ratio may indicate the market expects significant growth or profitability.
- Enterprise Value to EBITDA Ratio: This metric divides enterprise value by EBITDA (Earnings Before Interest, Taxes, Depreciation, and Amortization). It’s often used to evaluate a company’s operating performance by comparing its overall value to its operating earnings. It’s frequently applied in acquisition analysis, as it shows how many times EBITDA investors are willing to pay for the company.
Extracting Quarterly Balance Sheet
The function extract_balancesheet_quarterly
retrieves quarterly balance sheet data for the company, but can also fetch yearly data.
def extract_balancesheet_quarterly(symbol):
# Purpose: Fetch quarterly balance sheet data for a stock symbol.
raw_df= client.get_fundamentals_data(symbol)
df = pd.DataFrame(raw_df['Financials']['Balance_Sheet']['quarterly']).T
return df
Extracting Earnings Trends
The function extract_earning_trends
gathers earnings insights, including growth rates and analyst estimates.
def extract_earning_trends(symbol):
# Purpose: Collect earning trends data for a stock symbol.
raw_df= client.get_fundamentals_data(symbol)
df = pd.DataFrame(raw_df['Earnings']['Trend']).T
return df
Here’s an overview of the information it returns:
- Growth: Represents the percentage growth in earnings.
- Earnings Estimate Avg: The average earnings estimate, based on analyst forecasts.
- Earnings Estimate Low/High: The lowest and highest earnings estimates provided.
- Earnings Estimate Year Ago EPS: The earnings per share (EPS) from the same period in the previous year, allowing for historical comparison.
- Earnings Estimate Number Of Analysts: Shows the number of analysts contributing to the earnings estimates.
- Earnings Estimate Growth: Displays the growth rate of the earnings estimates, indicating the expected earnings trend.
- Revenue Estimate Avg: The average revenue estimate, reflecting market expectations.
- Revenue Estimate Growth: The rate of revenue growth according to analyst projections.
- EPS Trend (Current, 7 days ago, 30 days ago, 60 days ago, 90 days ago): Shows trends in EPS estimates across different recent time frames, providing insight into how estimates are evolving.
- EPS Revisions (Up/Down) Last 7 days and 30 days: The number of upward and downward revisions in earnings estimates over the last 7 and 30 days, offering an indication of changing analyst sentiment.
Extracting Analyst Ratings
The function extract_analystR
obtains analyst recommendations, which include ratings like Strong Buy, Buy, Hold, Sell, and Strong Sell.
def extract_analystR(symbol):
# Purpose: Extract analyst ratings for a stock symbol.
raw_df= client.get_fundamentals_data(symbol)
df = pd.DataFrame([raw_df['AnalystRatings']])
return df
extract_analystR('TSLA')
Explanation of output fields:
- Strong Buy: Expected high performance.
- Buy: Positive recommendation.
- Hold: Neutral outlook.
- Sell: Expected decline.
- Target Price: Fair future value estimate.
Extracting Highlights
The extract_highlights
function provides key highlights for a stock, such as market cap and earnings metrics.
def extract_highlights(symbol):
# Purpose: Retrieve highlights data for a stock symbol.
raw_df= client.get_fundamentals_data(symbol)
df = pd.DataFrame([raw_df['Highlights']])
return df
Here are the main fields it returns:
- Market Capitalization: Total market value of a company’s outstanding shares.
- EBITDA (Earnings Before Interest, Taxes, Depreciation, and Amortization): Indicator of operating performance.
- PE Ratio (Price-to-Earnings Ratio): Measures stock valuation relative to earnings.
- PEG Ratio (Price/Earnings to Growth Ratio): Assesses stock valuation considering earnings growth.
- Wall Street Target Price: Analysts’ estimated future stock price.
- Book Value: Net asset value of a company’s shares.
- Dividend Share & Dividend Yield: Cash paid per share and yield based on the dividend.
- Earnings Share: The company’s profit distributed to each outstanding share.
- Profit Margin & Operating Margin TTM (Trailing Twelve Months): Measures profitability.
- Return on Assets and Return on Equity TTM: Indicate company efficiency in using assets and equity.
- Revenue TTM (Trailing Twelve Months) & Revenue Per Share TTM: Total revenue and revenue per share.
- Quarterly Revenue Growth YoY (Year-over-Year): Growth in revenue compared to the same quarter in the previous year.
- Gross Profit TTM: Total revenue minus the cost of goods sold.
- Diluted EPS TTM: Earnings per share, accounting for all potential dilution.
- Quarterly Earnings Growth YoY: Growth in earnings compared to the same quarter in the previous year.
Extracting Technicals
The extract_technicals
function fetches technical indicators like Beta and moving averages for trend analysis.
def extract_technicals(symbol):
# Purpose: Get technicals-related information for a stock symbol.
raw_df= client.get_fundamentals_data(symbol)
df = pd.DataFrame([raw_df['Technicals']])
return df
extract_technicals('TSLA')
Output Fields:
- Beta: Reflects a stock’s volatility compared to the overall market. A beta of 1 indicates that the stock moves in sync with the market; below 1 suggests less volatility, while above 1 signals higher volatility.
- 52-Week High & 52-Week Low: The peak and lowest prices a stock has reached in the last 52 weeks, highlighting its historical price range.
- 50-Day Moving Average (50DayMA) & 200-Day Moving Average (200DayMA): These are averages of the stock’s closing prices over the previous 50 and 200 days, respectively. They help identify trends and potential levels of support or resistance.
- Shares Short & Shares Short Prior Month: Number of shares shorted by investors, representing bets that the stock price will drop, shown for both the current and previous months.
- Short Ratio: The estimated number of days required for short sellers to cover their positions based on average daily trading volume, offering insight into possible pressure on the stock.
- Short Percent: The proportion of outstanding shares that are shorted, providing a sense of market sentiment and the potential for short squeezes.
This technical data aids in evaluating stock price trends, volatility, and market sentiment, offering valuable indicators for investment strategies.
Creating Dynamic Variables for Each Stock
This code dynamically generates variables for each stock symbol, storing specific data types in globally accessible dataframes.
# Given list of stock symbols
stock_list = ['TSLA', 'IBM', 'MSFT', 'AAPL']
# Loop through each stock symbol and dynamically create variables using globals()
for i in stock_list:
globals()[i + '_fundamental'] =extract_fundamentals(i)
globals()[i + '_valuation'] =extract_valuation(i)
globals()[i + '+_balancesheet_quarterly'] =extract_balancesheet_quarterly(i)
globals()[i + '_earning_trends'] =extract_earning_trends(i)
globals()[i + '_esgscores'] =extract_esgscores(i)
globals()[i + '_analystR'] =extract_analystR(i)
globals()[i + '_highlights'] =extract_highlights(i)
globals()[i + '_technicals'] =extract_technicals(i)
This code provides a structured approach to analyzing various aspects of companies’ financials using the EODHD API.
Visualizing the Fundamentals of Different Companies
To better understand and compare the fundamentals of various companies, we’ll use Seaborn to create line plots for key metrics like valuation and analyst ratings.
# Concatenate the dataframes
valuation_df = pd.concat([IBM_valuation, Tsla_valuation, AAPL_valuation, MSFT_valuation]).reset_index()
analyst_df = pd.concat([IBM_analystR, Tsla_analystR, AAPL_analystR, MSFT_analystR]).reset_index()
highlights_df = pd.concat([IBM_highlights, Tsla_highlights, AAPL_highlights, MSFT_highlights]).reset_index()
technicals_df = pd.concat([IBM_technicals, Tsla_technicals, AAPL_technicals, MSFT_technicals]).reset_index()
valuation_df
This code combines the data for IBM, Tesla (TSLA), Apple (AAPL), and Microsoft (MSFT) into single dataframes. The resulting valuation_df
, analyst_df
, highlights_df
, and technicals_df
dataframes allow for straightforward comparisons across these companies.
Output:
# Set the style of seaborn
sns.set(style="whitegrid")
# Create the first line plot
sns.lineplot(x = valuation_df.index, y=valuation_df['EnterpriseValue'])
plt.show()
Output:
When comparing the enterprise values of IBM, Tesla, Apple, and Microsoft, we found that Apple has the highest total value, accounting for its market capitalization, debt, and cash. In contrast, IBM has the lowest enterprise value among these companies.
display(analyst_df)
Output:
sns.lineplot(x =analyst_df.index, y=analyst_df['Rating'],label='Line 2')
Output:
The trend indicates that analysts have recommended trading Microsoft’s stock more frequently than that of the other companies in the comparison.
display(highlights_df)
Output:
sns.lineplot(x =highlights_df.index, y=highlights_df['PERatio'],label='Line 3')
Output:
The PE Ratio (Price-to-Earnings Ratio) assesses a stock’s valuation in relation to its earnings. The trend shows that Tesla’s PE ratio is higher than that of the other companies in the comparison.
sns.lineplot(x =highlights_df.index, y=highlights_df['EBITDA'],label='Line 4')
Output:
EBITDA (Earnings Before Interest, Taxes, Depreciation, and Amortization) serves as a key indicator of operating performance. Based on this metric, Apple demonstrates stronger operating performance compared to the other three companies in this analysis.
Conclusion: Building a Strong Foundation for Smart Investing
When navigating the stock market, it’s easy to get caught up in the flashy trends and complex charts. But the real power lies in understanding the core fundamentals of a company. With EODHD APIs as your resource, fundamental analysis becomes a straightforward and invaluable part of your investing strategy. By combining a solid grasp of fundamental data with EODHD’s comprehensive tools, you’re not only investing — you’re making informed, strategic decisions.
Happy investing!
Stay tuned for more valuable articles that aim to enhance your data science skills and market analysis capabilities.
The original article was published in the EODHD Academy by Nikhil Adithyan
Please note that this article is for informational purposes only and should not be taken as financial advice. We do not bear responsibility for any trading decisions made based on the content of this article. Readers are advised to conduct their research or consult with a qualified financial professional before making any investment decisions.
For those eager to delve deeper into such insightful articles and broaden their understanding of different strategies in financial markets, we invite you to follow our account and subscribe for email notifications.