Python code to find stock with certain PE ratio

The following lists stock with price to earnings ratio (PE) less than 30. This code uses a third-party API to fetch stock data, and the API’s data may not be up-to-date or accurate. You should always verify the data before making any investment decisions.

Code

import requests
import json

def get_price_to_earnings_ratio(symbol):
  # Fetch the data for a stock using its symbol
  response = requests.get(f"https://financialmodelingprep.com/api/v3/company/price-to-earnings/{symbol}")
  data = json.loads(response.text)

  # Return the price to earnings ratio
  return data["priceToEarnings"]["PE"]

# A list of stock symbols
symbols = ["AAPL", "GOOG", "MSFT", "IBM", "FB"]

# Find all stocks with a price to earnings ratio less than 5
for symbol in symbols:
  pe = get_price_to_earnings_ratio(symbol)
  if pe < 30:
    print(f"{symbol} has a price to earnings ratio of {pe}")

Explanation

This code is written in Python and uses the requests and json libraries. It performs the following actions:

  1. Imports the requests and json libraries. The requests library is used to make HTTP requests to an API, and the json library is used to parse the data returned by the API.
  2. Defines a function get_price_to_earnings_ratio(symbol) that takes a stock symbol as an argument and returns the stock’s price-to-earnings (P/E) ratio.
  • Within the function, it uses the requests.get method to make a GET request to a financial data API (https://financialmodelingprep.com/api/v3/company/price-to-earnings/{symbol}), where {symbol} is replaced by the passed symbol.
  • The response object returned by the requests.get method contains the data returned by the API. The json.loads method is used to parse the JSON data contained in the response, and the result is stored in a data variable.
  • The P/E ratio is then returned by accessing the data["priceToEarnings"]["PE"] field.
  1. Defines a list of stock symbols, symbols = ["AAPL", "GOOG", "MSFT", "IBM", "FB"].
  2. Uses a for loop to iterate over the symbols and find all stocks with a P/E ratio less than 5.
  • For each symbol, the get_price_to_earnings_ratio function is called, and the result is stored in a pe variable.
  • If the P/E ratio is less than 5, the symbol and its P/E ratio are printed to the console.

This code provides a basic example of how to fetch financial data for a stock and find stocks with a P/E ratio less than a specified threshold.

Unit Test

import unittest
from unittest.mock import Mock, patch
import requests
import json

class TestGetPriceToEarningsRatio(unittest.TestCase):
def test_get_price_to_earnings_ratio(self):
# Test data
symbol = “AAPL”
pe = 15.44

    # Create a mock response object
    mock_response = Mock()
    mock_response.text = json.dumps({"priceToEarnings": {"PE": pe}})

    # Use the patch decorator to replace the requests.get method with our mock response
    with patch('requests.get', return_value=mock_response):
        from main import get_price_to_earnings_ratio

        # Call the function and assert that the returned value is correct
        result = get_price_to_earnings_ratio(symbol)
        self.assertEqual(result, pe)

if name == ‘main‘:
unittest.main()

In this example, the unittest library is used to define a test case class TestGetPriceToEarningsRatio. This class has a single test method test_get_price_to_earnings_ratio that tests the get_price_to_earnings_ratio function.

The test data consists of a symbol "AAPL" and a P/E ratio 15.44.

The requests.get method is mocked using the patch decorator, so that it returns a mock response object instead of making an actual API request. The mock response object is created using the unittest.mock.Mock class and has a text attribute that contains a JSON string representing the expected API response.

The test case uses the assertEqual method to check that the function returns the expected P/E ratio.

The test can be run using the python -m unittest command in the terminal.