top of page
  • Nikhil Adithyan

Finding the Best Sector to Invest in using Python

Updated: Jan 3

Navigating the task of picking the right sector using APIs




Introduction

In your trading journey, whether you’re looking for the ideal stock, sector, or indicators, making informed decisions is paramount for your success. However, gathering and analyzing the vast amount of data required can be quite daunting. Bulk Endpoint of the Financial Modeling Prep (FMP) API simplifies this process by providing data for numerous companies with just a single click.


Why is this data so valuable? Well, it’s an asset that can be applied in various ways, especially for both Fundamental and Technical analysis. By comparing data from different companies, you can uncover which one is your best choice in the current market scenario, based on past and present data.


For instance, you can use this data to identify the most promising sector to invest in.


In this article, we’ll guide you through exploring and effectively applying the data from the Bulk Endpoints of the FMP API, making the complex world of trading data accessible and actionable.


1. Importing the Packages

It’s essential to set up the right tools. These packages will help you with the capabilities needed to access, process, and analyze the wealth of data you’re about to explore.


# IMPORTING PACKAGES

import requests
import pandas as pd
from io import StringIO

Requests: Used for making HTTP requests to access data from web APIs.


Pandas: Provides data manipulation and analysis tools for working with structured data.


StringIO: Allows working with in-memory text data as if it were a file.

If you haven’t installed any of the imported packages, make sure to do so using the pip command in your terminal.


2. Exploring the bulk endpoints

With your tools in place, it’s time to navigate to the bulk endpoints of the FMP API. The endpoints are a source of immense data.


Accessing any of these endpoints follows the same steps, detailed further as a code snippet. Exploring these endpoints provides a comprehensive understanding of the available data, offering a wide range of information accessible with a single click, covering multiple companies and various financial aspects. This step aims to make you familiar with the data sources at your disposal.


For our application, we will utilize the income statement endpoint to analyze a sector for potential investment. Feel free to combine multiple data points to suit your needs.


api_key = 'YOUR API KEY'
url = f'https://financialmodelingprep.com/api/v4/income-statement-bulk?year=2020&period=annual&apikey={api_key}'
response = requests.get(url)
df_income = pd.read_csv(StringIO(response.text))

Use your API to make requests to the various URL endpoints and convert them to dataframes using the above code.


3. Data Preprocessing

Data preprocessing is the vital step of cleaning and organizing the information you’ve acquired. The process transforms raw data into a usable form, making it ready for your trading insights.


df_income  = df_income[['symbol','date','revenue', 'grossProfit', 'operatingIncome', 'EBITDA', 'netIncome']]

We choose these columns from the dataset to decide the sector.


‘revenue’: Total revenue is a fundamental indicator of a company’s financial health.


‘grossProfit’: Gross profit is a measure of profitability before operating expenses.


‘operatingIncome’: Operating income shows how well a company is performing in its core operations.


‘EBITDA’: Earnings Before Interest, Taxes, Depreciation, and Amortization is a key metric for assessing operating performance.


‘netIncome’: Net income is the bottom line and represents the company’s profitability after all expenses.


Using these three industry giants as representative examples for each sector, we have selected Apple, Google, and Microsoft to symbolize the technology sector. In the same lines, for healthcare and finance sectors, we chose Johnson & Johnson (JNJ), Pfizer Inc. (PFE), UnitedHealth Group Inc. (UNH), JPMorgan Chase & Co. (JPM), The Goldman Sachs Group, Inc. (GS), and Citigroup Inc. ©. These companies serve as barometers for their respective sectors. A decline in their performance parameters often signals a weakening sector. Feel free to use multiple companies as sector indicators.



Technology = df_income.loc[(df_income['symbol'] == 'AAPL') | (df_income['symbol'] == 'GOOGL') | (df_income['symbol'] == 'MSFT')]
Healthcare = df_income.loc[(df_income['symbol'] == 'JNJ') | (df_income['symbol'] == 'PFE') | (df_income['symbol'] == 'UNH')]3
Finance = df_income.loc[(df_income['symbol'] == 'JPM') | (df_income['symbol'] == 'GS') | (df_income['symbol'] == 'C')]

Technology.sum(axis = 0)

Technology:



Healthcare:


Healthcare.sum()


Finance:


Finance.sum()


4. Finding the right sector

By comparing and analyzing this data, you’ll be able to pinpoint the sectors that show the most potential for your investment strategies. It strengthens us to make informed decisions when selecting the right sector to invest in.



def findSector(tech, health, finance):
    h = 0
    t = 0
    f = 0
    
    for i in ['revenue', 'grossProfit', 'operatingIncome', 'EBITDA', 'netIncome']:
        if tech.sum()[i] > health.sum()[i] and tech.sum()[i] > finance.sum()[i]:
            t = t + 1
        if health.sum()[i] > tech.sum()[i] and health.sum()[i] > finance.sum()[i]:
            h = h + 1
        if finance.sum()[i]>tech.sum()[i] and finance.sum()[i]>health.sum()[i]:
            f = f + 1  
    if f > t and f > h:
        print('Invest In Finance')
    if h > t and h > f:
        print('Invest in Healthcare')
    else:
        print('Invest in Healthcare')  

findSector(Technology, Healthcare, Finance)

Output:


Invest in Healthcare

This function takes three data frames as arguments: tech, health, and finance. It compares the total sums of specific financial metrics, such as revenue, gross profit, operating income, EBITDA, and net income, for three sectors: technology (tech), healthcare (health), and finance (finance). The code iterates through these metrics, counting how many times one sector’s total sum is greater than the other two sectors for each metric. Based on these counts, it determines which sector has the highest total sum across the metrics.


In our case, it is the healthcare sector to invest in rather than the other two sectors, by comparing the important indicators of the representative companies.


Conclusion

The article demonstrates the remarkable potential of the Financial Modeling Prep (FMP) API’s Bulk Endpoints in streamlining access to trading data. It acts as a pivotal tool for well-informed trading choices by providing a dataset suitable for both Fundamental and Technical analysis.


In the world of trading, where data reigns supreme, the FMP API’s Bulk Endpoints offer traders and investors a powerful means to make data-backed decisions. It’s a transformative resource for those seeking success in their trading endeavors.


With that being said, you’ve reached the end of the article. Hope you learned something new and useful today. Let me know what you think of this API in the comments. Thank you for your time.

1 comment
bottom of page