FMP

FMP

Enter

Retrieve Company Fundamentals with Python

-

twitterlinkedinfacebook
blog post cover photo

Image credit: Benjamin Child

In this new post on Python for Finance, we are going to build an amazing Python tool to retrieve company fundamentals. It will be super simple to use.

We will pass the ticker of the company that we are interested in and Python will do its magic to show us below Pandas DataFrame converted into an Excel file.

Photo by Pixabay on Pexels

Below is just a sample for Apple. All main Apple fundamentals are basically presented to us thanks to this powerful script:

The main goal of the code is to get company financials from the last 5 years. Then, calculate some growth metrics and export to an Excel file. I would state below the main steps to achieve this:

  • Request data from the financialmodelingprep.

  • Load into a Python variable the main financial data requested from the API. That is, IS, BS, CF and main financial ratios.

  • Create an empty dictionary in order to store the values using the respective year as the key.

  • Transform the dictionary into a Pandas DataFrameCalculate a few growth measures as new columns

  • Export to Excel

And here is the code:

import pandas as pd

pd.options.display.float_format = '{:,.2f}'.format

#pass ticker of the company

company = 'AAPL'

api = 'your api key'

# Request Financial Data from API and load to variables

IS = requests.get(f'https://financialmodelingprep.com/api/v3/income-statement/{company}?apikey={api}').json()

BS = requests.get(f'https://financialmodelingprep.com/api/v3/balance-sheet-statement/{company}?apikey={api}').json()

CF = requests.get(f'https://financialmodelingprep.com/api/v3/cash-flow-statement/{company}?apikey={api}').json()

Ratios = requests.get(f'https://financialmodelingprep.com/api/v3/ratios/{company}?apikey={api}').json()

key_Metrics = requests.get(f'https://financialmodelingprep.com/api/v3/key-metrics/{company}?apikey={api}').json()

profile = requests.get(f'https://financialmodelingprep.com/api/v3/profile/{company}?apikey={api}').json()

millions = 1000000

#Create empty dictionary and add the financials to it

financials = {}

dates = [2021,2020,2019,2018,2017]

for item in range(5):

financials[dates[item]] ={}

#Key Metrics

financials[dates[item]]['Mkt Cap'] = key_Metrics[item]['marketCap'] /millions

financials[dates[item]]['Debt to Equity'] = key_Metrics[item]['debtToEquity']

financials[dates[item]]['Debt to Assets'] = key_Metrics[item]['debtToAssets']

financials[dates[item]]['Revenue per Share'] = key_Metrics[item]['revenuePerShare']

financials[dates[item]]['NI per Share'] = key_Metrics[item]['netIncomePerShare']

financials[dates[item]]['Revenue'] = IS[item]['revenue'] / millions

financials[dates[item]]['Gross Profit'] = IS[item]['grossProfit'] / millions

financials[dates[item]]['R&D Expenses'] = IS[item]['researchAndDevelopmentExpenses']/ millions

financials[dates[item]]['Op Expenses'] = IS[item]['operatingExpenses'] / millions

financials[dates[item]]['Op Income'] = IS[item]['operatingIncome'] / millions

financials[dates[item]]['Net Income'] = IS[item]['netIncome'] / millions

financials[dates[item]]['Cash'] = BS[item]['cashAndCashEquivalents'] / millions

financials[dates[item]]['Inventory'] = BS[item]['inventory'] / millions

financials[dates[item]]['Cur Assets'] = BS[item]['totalCurrentAssets'] / millions

financials[dates[item]]['LT Assets'] = BS[item]['totalNonCurrentAssets'] / millions

financials[dates[item]]['Int Assets'] = BS[item]['intangibleAssets'] / millions

financials[dates[item]]['Total Assets'] = BS[item]['totalAssets'] / millions

financials[dates[item]]['Cur Liab'] = BS[item]['totalCurrentLiabilities'] / millions

financials[dates[item]]['LT Debt'] = BS[item]['longTermDebt'] / millions

financials[dates[item]]['LT Liab'] = BS[item]['totalNonCurrentLiabilities'] / millions

financials[dates[item]]['Total Liab'] = BS[item]['totalLiabilities'] / millions

financials[dates[item]]['SH Equity'] = BS[item]['totalStockholdersEquity'] / millions

financials[dates[item]]['CF Operations'] = CF[item]['netCashProvidedByOperatingActivities'] / millions

financials[dates[item]]['CF Investing'] = CF[item]['netCashUsedForInvestingActivites'] / millions

financials[dates[item]]['CF Financing'] = CF[item]['netCashUsedProvidedByFinancingActivities'] / millions

financials[dates[item]]['CAPEX'] = CF[item]['capitalExpenditure'] / millions

financials[dates[item]]['FCF'] = CF[item]['freeCashFlow'] / millions

financials[dates[item]]['Dividends Paid'] = CF[item]['dividendsPaid'] / millions

#Income Statement Ratios

financials[dates[item]]['Gross Profit Margin'] = Ratios[item]['grossProfitMargin']

financials[dates[item]]['Op Margin'] = Ratios[item]['operatingProfitMargin']

financials[dates[item]]['Int Coverage'] = Ratios[item]['interestCoverage']

financials[dates[item]]['Net Profit Margin'] = Ratios[item]['netProfitMargin']

financials[dates[item]]['Dividend Yield'] = Ratios[item]['dividendYield']

#BS Ratios

financials[dates[item]]['Current Ratio'] = Ratios[item]['currentRatio']

financials[dates[item]]['Operating Cycle'] = Ratios[item]['operatingCycle']

financials[dates[item]]['Days of AP Outstanding'] = Ratios[item]['daysOfPayablesOutstanding']

financials[dates[item]]['Cash Conversion Cycle'] = Ratios[item]['cashConversionCycle']

#Return Ratios

financials[dates[item]]['ROA'] = Ratios[item]['returnOnAssets']

financials[dates[item]]['ROE'] = Ratios[item]['returnOnEquity']

financials[dates[item]]['ROCE'] = Ratios[item]['returnOnCapitalEmployed']

financials[dates[item]]['Dividend Yield'] = Ratios[item]['dividendYield']

#Price Ratios

financials[dates[item]]['PE'] = Ratios[item]['priceEarningsRatio']

financials[dates[item]]['PS'] = Ratios[item]['priceToSalesRatio']

financials[dates[item]]['PB'] = Ratios[item]['priceToBookRatio']

financials[dates[item]]['Price To FCF'] = Ratios[item]['priceToFreeCashFlowsRatio']

financials[dates[item]]['PEG'] = Ratios[item]['priceEarningsToGrowthRatio']

financials[dates[item]]['EPS'] = IS[item]['eps']

financials[dates[item]]['EPS'] = IS[item]['eps']

#Transform the dictionary into a Pandas

fundamentals = pd.DataFrame.from_dict(financials,orient='columns')

#Calculate Growth measures

fundamentals['CAGR'] = ((fundamentals[2021]/fundamentals[2017])**(1/5) - 1

fundamentals['2021 growth'] = (fundamentals[2021] - fundamentals[2020] )/ fundamentals[2020]

fundamentals['2020 growth'] = (fundamentals[2020] - fundamentals[2019] )/ fundamentals[2019]

fundamentals['2019 growth'] = (fundamentals[2019] - fundamentals[2018] )/ fundamentals[2018]

fundamentals['2018 growth'] = (fundamentals[2018] - fundamentals[2017] )/ fundamentals[2017]

#Export to Excel

fundamentals.to_excel('fundamentals.xlsx')

print(fundamentals)

Once the script runs, Python should create an Excel file including all company fundamentals.

Other Blogs

Aug 7, 2024 3:53 AM - Parth Sanghvi

The Impact of Interest Rates on the Economy and Financial Markets: A Comprehensive Analysis

Interest rates play a crucial role in the economy and financial markets, influencing everything from consumer behavior to investment decisions. Understanding their impact is essential for making informed financial and investment decisions. This comprehensive analysis delves into how interest rates a...

blog post title

Sep 10, 2024 7:33 AM - Parth Sanghvi

Best Alternatives to Yahoo Finance for Downloading Historical Stock Data

When it comes to downloading historical stock data, Yahoo Finance has been a popular choice for many. However, for those looking for more comprehensive, accurate, and flexible options, Financial Modeling Prep (FMP) offers a suite of powerful tools and services that stand out as superior alternatives...

blog post title

Nov 8, 2024 5:30 AM - Sanzhi Kobzhan

Understanding Equity Valuation: When to Use DCF, DDM, and Price-Income (Multiplicators) Models

When it comes to investing in stocks, one of the key decisions an investor must make involves determining the intrinsic value of a company's shares. Equity valuation isn't just about numbers, it's an art mixed with science, aiming to predict future performance based on current and historical data. H...

blog post title
FMP

FMP

Financial Modeling Prep API provides real time stock price, company financial statements, major index prices, stock historical data, forex real time rate and cryptocurrencies. Financial Modeling Prep stock price API is in real time, the company reports can be found in quarter or annual format, and goes back 30 years in history.
twitterlinkedin
2017-2025 © Financial Modeling Prep