How to pull Stock Information using the FMP API with Python

Accurately analysing stock information, beit price or some ratio, is crucial to making informed investment decisions. Many analysts still use traditional analyt

How to pull Stock Information using the FMP API with Python

Sep 29, 2022 9:28 PM - Jack Dalton

twitterlinkedinfacebook
blog post cover photo

Image credit: Markus Spiske

Accurately analysing stock information, beit price or some ratio, is crucial to making informed investment decisions. Many analysts still use traditional analytical methods with a software like Microsoft Excel but many are turning to data science to leverage the power of languages like Python. In this article, we will teach you the most basic step required to start using Python for analysing stock information. Here is a guide on how to pull stock information using the FMP Stock Market API.

Step 1: Load FMP Developer API Docs Website

From this article go to the top right of the page, click “Developers” and then click "API Docs" from the list below. Make sure you are logged into your account. You should see this in the top right corner:

image

Otherwise, click login and enter your account credentials.

A key piece of information that'll want to write down in a safely secured location is your API Key. This is located in the second section of the API docs page which is called "Your Details". See in the example below, it should be a long series of letters and numbers. As with any key, this unlocks something and in this case it ensures that you have permission to access the API you are requesting. Make sure to keep your key private and safely secured if you are storing it somewhere on your computer. It is against our terms and conditions to share your API key with anyone - your account will be blocked and investigated if we suspect you are doing this.

Step 2: Copy the URL for the API you want to access

For this example, we are going to pull from the company profile API. So scroll down to the section that says Stock Price (You can also use the navigation bar on the left hand side of the screen) and you will see the following:

image

Then right click on the box that contains something that looks like a condensed URL. In this case: api/v3/quote/APPL

Step 3: Open Your Python Environment and copy URL

Now you'll need to open up your Python environment to start writing code. To start with, create a variable called “URL” and give the string version of the URL you copied in step 2. You can simply use Ctrl + V (or cmd + V for mac users) to paste the url you copied.

ERROR ALERT: Make sure to add inverted commas (otherwise called quotation marks) around the copied URL to make the URL variable a string.

url = “https://financialmodelingprep.com/api/v3/quote/AAPL?apikey=demo”

If you're copying directly from this page you'll need to make sure that you replace the ‘demo' with your API key

Step 4: Write the Python code to access the Financial Statement

To learn more about exactly what all the following code means and why it works, visit out guide - How to call a Financial Modeling Prep API

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 json def get_jsonparsed_data(url): """ Receive the content of ``url``, parse it as JSON and return the object. Parameters ---------- url : str Returns ------- dict """ response = urlopen(url) data = response.read().decode("utf-8") return json.loads(data) url = ("https://financialmodelingprep.com/api/v3/quote/AAPL?apikey=demo") Quote_APPL = get_jsonparsed_data(url)

The FMP Quote API will return a JSON format data packet which will include the following bits of information:

  • symbol
  • name
  • price
  • changesPercentage
  • change
  • dayLow
  • dayHigh
  • yearHigh
  • yearLow
  • marketCap
  • priceAvg50
  • priceAvg200
  • volume
  • avgVolume
  • exchange
  • open
  • previousClose
  • eps
  • pe
  • earningsAnnouncement
  • sharesOutstanding
  • timestamp

We've left this in the exact format that comes out of the API so that you can easily copy and paste!

Step 5: Look inside the data you just received!

If you're working in a JupyterLab environment you'll be able to see the JSON data you received by simply typing in the name of the variable you've stored the information under and hitting enter. As you can see on the last line of code above, we've named our variable Quote_APPL. If you're working in a regular python environment and want to print the data then use the following:

print(Quote_APPL)

This prints out the JSON format dictionary.

Step 6: Get a specific data point from the larger JSON data provided

Often it's good to take a look at the one basic stock quote delivered to be able to see the way everything has been stored. Assuming you're using JupyterLab, enter the following code to look at the most recent statement:

Quote_APPL[0]

You should see something like this:

image

Now I'm going to show you how to pull one data point from this set. You'll need to index into the particular statement (note that you index in using a number from 0 to the limit you set minus 1) and then index the element of the statement you want to extract. Here's how you could pull the day low for APPL:

Quote_APPL[0][‘dayLow']

ERROR ALERT: To ensure you don't get a DNE error, make sure to directly copy the name of the stock quote element from the sample view generated from printing the received quote.

So there you have it, it's as easy as that to start receiving stock quotes using the Financial Modeling Prep API! Now here's a few bonus things that you can get from FMP API's that may help get you going!

Stock Profile

URL: api/v3/profile/AAPL?apikey=

Data Received: 'symbol', 'price', 'beta', 'volAvg', 'mktCap', 'lastDiv', 'range', 'changes', 'companyName', 'currency', 'cik', 'isin', 'cusip', 'exchange', 'exchangeShortName', 'industry', 'website', 'description', 'ceo', 'sector', 'country', 'fullTimeEmployees', 'phone', 'address', 'city', 'state', 'zip', 'dcfDiff', 'dcf', 'image', 'ipoDate', 'defaultImage', 'isEtf', 'isActivelyTrading'

Stock Rating

URL: api/v3/rating/AAPL?apikey=

Data Received: 'symbol', 'date', 'rating', 'ratingScore', 'ratingRecommendation', 'ratingDetailsDCFScore', 'ratingDetailsDCFRecommendation', 'ratingDetailsROEScore', 'ratingDetailsROERecommendation', 'ratingDetailsROAScore', 'ratingDetailsROARecommendation', 'ratingDetailsDEScore', 'ratingDetailsDERecommendation', 'ratingDetailsPEScore', 'ratingDetailsPERecommendation', 'ratingDetailsPBScore', 'ratingDetailsPBRecommendation'

Quaterly Stock Metrics

URL: api/v3/key-metrics/AAPL?period=quarter&limit=130&apikey=

Data Received: 'symbol', 'date', 'period', 'revenuePerShare', 'netIncomePerShare', 'operatingCashFlowPerShare', 'freeCashFlowPerShare', 'cashPerShare', 'bookValuePerShare', 'tangibleBookValuePerShare', 'shareholdersEquityPerShare', 'interestDebtPerShare', 'marketCap', 'enterpriseValue', 'peRatio', 'priceToSalesRatio', 'pocfratio', 'pfcfRatio', 'pbRatio', 'ptbRatio', 'evToSales', 'enterpriseValueOverEBITDA', 'evToOperatingCashFlow', 'evToFreeCashFlow', 'earningsYield', 'freeCashFlowYield', 'debtToEquity', 'debtToAssets', 'netDebtToEBITDA', 'currentRatio', 'interestCoverage', 'incomeQuality', 'dividendYield', 'payoutRatio', 'salesGeneralAndAdministrativeToRevenue', 'researchAndDdevelopementToRevenue', 'intangiblesToTotalAssets', 'capexToOperatingCashFlow', 'capexToRevenue', 'capexToDepreciation', 'stockBasedCompensationToRevenue', 'grahamNumber', 'roic', 'returnOnTangibleAssets', 'grahamNetNet', 'workingCapital', 'tangibleAssetValue', 'netCurrentAssetValue', 'investedCapital', 'averageReceivables', 'averagePayables', 'averageInventory', 'daysSalesOutstanding', 'daysPayablesOutstanding', 'daysOfInventoryOnHand', 'receivablesTurnover', 'payablesTurnover', 'inventoryTurnover', 'roe', 'capexPerShare'

Other Blogs

Sep 29, 2022 - Jack Dalton

How to call the Financial Modeling Prep API with Python

Financial Modeling Prep has a suite of APIs to enable you to access the most valuable financial data out there. But what is an API and how does it work? Simply, an API is a gateway for people to send and receive data over the internet. FMP has free stock APIs, Financial Statement APIs, and many more...

blog post title

Sep 29, 2022 - Jack Dalton

Top 14 Best & Most Popular Stock Research Websites

Stock market research is important to let traders reach the entire performance history of the company in which they are planning to invest or buying stocks for future profitability. This information is crucial and contains the complete library of each listed company's financial performance (encompas...

blog post title

Sep 5, 2023 - Davit Kirakosyan

HashiCorp Reports Q2 Beat & Strong Guidance

HashiCorp (NASDAQ:HCP) reported its Q2 results, with earnings per share (EPS) of ($0.10), which surpassed the Street estimate of ($0.15). The company's revenue stood at $143.2 million, outperforming the Street estimate of $138.22 million. Looking ahead to Q3/24, HashiCorp projects EPS within the ran...

blog post title