Of course. Here is a complete Python solution for fetching NSE stock data based on your criteria.
Understanding the Challenge
The user wants to find stocks that meet two specific fundamental criteria:
- Low P/E Ratio: The stock's Price-to-Earnings (P/E) ratio should be lower than its Industry's average P/E. This is a classic value investing indicator.
- Strong Revenue Growth: The company should demonstrate consistent revenue growth, specified here as 10% annually.
Directly getting this data from a single, free, and reliable API can be difficult. For instance, yfinance can provide a stock's P/E but not the Industry P/E.
Therefore, the most effective approach is to leverage a financial data website that has already compiled this information and allows for screening. Screener.in is an excellent resource for Indian stocks that provides exactly this data.
This Python script will programmatically query screener.in and parse the results for you.
The Strategy
- Construct a Query: We will create a query that tells
screener.in to filter stocks based on our rules.
- Fetch the Results Page: Use the
requests library to download the HTML of the results page.
- Parse the HTML: Use
BeautifulSoup to find the results table within the HTML.
- Convert to a DataFrame: Use
pandas to neatly convert the HTML table into a structured DataFrame for easy viewing and further analysis.
Python Code
This script will find companies with:
- Market Capitalization > 500 Cr (to avoid very small, illiquid companies).
- Stock P/E < Industry P/E.
- Sales growth over the last 3 years (CAGR) > 10%. (Using 3-year growth is more robust than 1-year as it shows consistency).
Step 1: Install Necessary Libraries
First, you need to install the required Python libraries. Open your terminal or command prompt and run:
pip install requests pandas beautifulsoup4 lxml
Step 2: The Python Script
Create a new Python file (e.g., stock_screener.py) and paste the following code into it.
import requests
import pandas as pd
from bs4 import BeautifulSoup
def find_undervalued_growth_stocks():
"""
Fetches and displays NSE stocks that have a P/E lower than their
industry P/E and a 3-year sales growth CAGR greater than 10%.
This function scrapes data from screener.in.
"""
print("Finding undervalued stocks with strong revenue growth...")
# 1. Define the screening query
# We add "Market Capitalization > 500" to filter out very small companies.
# "Sales growth 3Years > 10" ensures consistent growth.
query = """
Market Capitalization > 500 AND
Price to Earning < Industry PE AND
Sales growth 3Years > 10
"""
# 2. Construct the URL and send a request
try:
# The base URL for the screener
base_url = "https://www.screener.in/screen/new/"
# We must send headers to mimic a browser request
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
# The query is passed as a URL parameter
response = requests.get(base_url, params={'query': query}, headers=headers)
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
except requests.exceptions.RequestException as e:
print(f"Error fetching data from screener.in: {e}")
return None
# 3. Parse the HTML response
soup = BeautifulSoup(response.text, 'lxml')
# Find the results table in the HTML. The table has a class 'data-table'.
results_table = soup.find('table', class_='data-table')
if results_table is None:
print("Could not find the results table. The website's structure might have changed.")
print("Please check the query on screener.in manually.")
return None
# 4. Use Pandas to read the HTML table into a DataFrame
try:
# pd.read_html returns a list of DataFrames. We want the first one.
df = pd.read_html(str(results_table))[0]
# 5. Clean up the DataFrame
# Drop the serial number column 'S.No.'
df = df.drop('S.No.', axis=1)
# The column names might have extra spaces, let's strip them
df.columns = df.columns.str.strip()
# Convert relevant columns to numeric, coercing errors to NaN
# This prevents the script from crashing if a value is missing (e.g., '-')
numeric_cols = ['Mar Cap Rs.Cr.', 'P/E', 'Ind P/E', 'Sales Qtr', 'Sales 3Yrs']
for col in numeric_cols:
if col in df.columns:
# The column names from screener can vary slightly, so we use flexible names
actual_col_name = [c for c in df.columns if col.replace(" ", "") in c.replace(" ", "")][0]
df[actual_col_name] = pd.to_numeric(df[actual_col_name], errors='coerce')
except Exception as e:
print(f"Error processing data with Pandas: {e}")
return None
return df
if __name__ == "__main__":
# Run the function and display the results
filtered_stocks_df = find_undervalued_growth_stocks()
if filtered_stocks_df is not None and not filtered_stocks_df.empty:
print("\n--- Found Stocks Matching Criteria ---")
print(f"Total stocks found: {len(filtered_stocks_df)}")
# To display all rows and columns without truncation
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 1000)
print(filtered_stocks_df)
print("\n--- End of List ---")
print("\nDisclaimer: Data is sourced from screener.in. Always do your own research before investing.")
elif filtered_stocks_df is not None:
print("\nNo stocks found matching the specified criteria at this time.")
else:
print("\nScript failed to retrieve data.")
How to Run the Script
- Save the code as
stock_screener.py.
- Open your terminal or command prompt.
- Navigate to the directory where you saved the file.
- Run the script using the command:
python stock_screener.py
Example Output
The output will be a table printed in your console, looking something like this (the actual stocks will vary based on current market data):
Finding undervalued stocks with strong revenue growth...
--- Found Stocks Matching Criteria ---
Total stocks found: 25
Name Mar Cap Rs.Cr. P/E Ind P/E Sales Qtr Sales 3Yrs ...
0 ABC Corporation Ltd 12345.67 15.50 25.80 12.50 18.20 ...
1 XYZ Tech Ltd 8765.43 20.10 35.50 22.00 15.60 ...
2 PQR Manufacturing Co 54321.00 18.75 22.10 15.75 11.90 ...
... ... ... ... ... ... ...
--- End of List ---
Disclaimer: Data is sourced from screener.in. Always do your own research before investing.
Important Disclaimers
- Web Scraping is Fragile: This script depends on the HTML structure of the
screener.in website. If they update their website, the script might break. It's intended for educational and personal use.
- Not Financial Advice: The results from this script are for informational purposes only. It's a starting point for your research, not a recommendation to buy or sell. Always perform thorough due diligence before making any investment decisions.
- Data Accuracy: The data is as accurate as the source (
screener.in). Always cross-verify with other sources if needed.