Below is a Python script to fetch NSE (National Stock Exchange of India) stock data based on your criteria: stocks with a low PE (Price-to-Earnings) ratio compared to their industry (sector) average PE, and a yearly revenue growth of at least 10%.
Key Assumptions and Notes:
Data Source: I'm using the yfinance library, which provides access to Yahoo Finance data. This includes NSE stocks (e.g., via tickers like 'INFY.NS'). Yahoo Finance isn't an official NSE source, but it covers NSE stocks and provides fundamental data like PE ratios and financial statements.
Stock Universe: To make this feasible, we'll limit the analysis to the Nifty 50 stocks (a major NSE index). You can expand this by providing a larger list of tickers.
PE Comparison: A stock's PE is considered "low" if it's less than the average PE of its sector.
Revenue Growth: We'll calculate year-over-year (YoY) revenue growth using the latest two annual revenue figures from the income statement. If the growth is >= 10%, the stock qualifies.
Dependencies: Install required libraries using pip install yfinance pandas.
Limitations:
Yahoo Finance data might not always be up-to-date or complete for all stocks.
This script performs web requests, so it may take time to run and could hit rate limits. Add delays if needed.
Always verify data from official sources before making investment decisions.
Python Code:
python
import yfinance as yf
import pandas as pd
import numpy as np
from typing import List
# List of Nifty 50 tickers (as of last update; you can update this list)
nifty_50_tickers = [
'RELIANCE.NS', 'HDFCBANK.NS', 'HINDUNILVR.NS', 'ICICIBANK.NS', 'INFY.NS',
'ITC.NS', 'SBIN.NS', 'LT.NS', 'BHARTIARTL.NS', 'ASIANPAINT.NS',
'KOKE.NS', 'AXISBANK.NS', 'DMART.NS', 'HINDALCO.NS', 'BAJFINANCE.NS',
'TCS.NS', 'SUNPHARMA.NS', 'NESTLEIND.NS', 'HCLTECH.NS', 'WIPRO.NS',
'TECHM.NS', 'ULTRACEMCO.NS', 'MARUTI.NS', 'ADANIGREEN.NS', 'ONGC.NS',
'TITAN.NS', 'POWERGRID.NS', 'ADANIPORTS.NS', 'NTPC.NS', 'BAJAJFINSV.NS',
'COALINDIA.NS', 'HEROMOTOCO.NS', 'DIVISLAB.NS', 'JSWSTEEL.NS', 'GRASIM.NS',
'BRITANNIA.NS', 'BAJAJ_AUTO.NS', 'DRREDDY.NS', 'TATASTEEL.NS', 'CIPLA.NS',
'M&M.NS', 'EICHERMOT.NS', 'HINDPETRO.NS', 'INDUSINDBK.NS', 'BPCL.NS',
'IOC.NS', 'SBILIFE.NS', 'PIDILITIND.NS', 'LTIM.NS', 'ADANIENT.NS'
]
def fetch_stock_data(tickers: List[str]) -> pd.DataFrame:
"""Fetch stock data including PE, sector, and revenue growth."""
data = [] # List to store results
for ticker in tickers:
try:
stock = yf.Ticker(ticker)
info = stock.info # Get basic info
# Extract PE ratio (trailing PE)
pe_ratio = info.get('trailingPE', np.nan) # Use trailing PE; handle missing data
# Extract sector
sector = info.get('sector', 'Unknown')
# Extract financials (income statement)
financials = stock.financials # DataFrame with financial items
if 'Total Revenue' in financials.index: # Check if revenue data is available
revenues = financials.loc['Total Revenue'] # Series with dates as index
revenues = revenues.sort_index(ascending=False) # Sort by date (newest first)
if len(revenues) >= 2: # Need at least two years of data
latest_revenue = revenues.iloc[0] # Most recent year
previous_revenue = revenues.iloc[1] # Previous year
# Calculate YoY revenue growth
revenue_growth = ((latest_revenue - previous_revenue) / previous_revenue) * 100
else:
revenue_growth = np.nan # Not enough data
else:
revenue_growth = np.nan # Revenue data not available
data.append({
'Ticker': ticker,
'PE Ratio': pe_ratio,
'Sector': sector,
'Revenue Growth (%)': revenue_growth
})
except Exception as e:
print(f"Error fetching data for {ticker}: {e}")
data.append({
'Ticker': ticker,
'PE Ratio': np.nan,
'Sector': 'Unknown',
'Revenue Growth (%)': np.nan
})
return pd.DataFrame(data)
def filter_stocks(df: pd.DataFrame) -> pd.DataFrame:
"""Filter stocks based on criteria: low PE compared to industry PE and revenue growth >= 10%."""
# Group by sector and calculate average PE
sector_avg_pe = df.groupby('Sector')['PE Ratio'].mean().to_dict()
filtered_data = []
for index, row in df.iterrows():
sector = row['Sector']
pe_ratio = row['PE Ratio']
revenue_growth = row['Revenue Growth (%)']
if sector in sector_avg_pe and not np.isnan(pe_ratio) and not np.isnan(revenue_growth):
industry_pe = sector_avg_pe[sector] # Average PE for the sector
if pe_ratio < industry_pe and revenue_growth >= 10:
filtered_data.append(row)
return pd.DataFrame(filtered_data)
# Main execution
if __name__ == "__main__":
print("Fetching data for Nifty 50 stocks...")
stock_data_df = fetch_stock_data(nifty_50_tickers)
print("Filtering stocks based on criteria...")
filtered_stocks_df = filter_stocks(stock_data_df)
if not filtered_stocks_df.empty:
print("Stocks meeting the criteria (low PE compared to industry PE and revenue growth >= 10%):")
print(filtered_stocks_df[['Ticker', 'PE Ratio', 'Sector', 'Revenue Growth (%)']])
else:
print("No stocks met the criteria.")
# Optionally, save to CSV
filtered_stocks_df.to_csv('filtered_nse_stocks.csv', index=False)
print("Results saved to 'filtered_nse_stocks.csv'.")
How the Code Works:
Fetching Data:
The fetch_stock_data function loops through the list of tickers.
For each stock, it uses yfinance to get:
PE ratio from stock.info.
Sector from stock.info.
Revenue data from stock.financials, then calculates YoY growth.
It stores the results in a Pandas DataFrame.
Filtering Data:
The filter_stocks function:
Groups the DataFrame by sector and computes the average PE for each sector.
For each stock, checks if:
Its PE is less than the sector's average PE.
Its revenue growth is at least 10%.
Returns a new DataFrame with only the qualifying stocks.
Output:
The script prints the filtered stocks and saves them to a CSV file for easy viewing.
Example output might look like:
code
Stocks meeting the criteria:
Ticker PE Ratio Sector Revenue Growth (%)
0 INFY.NS 25.3 Technology 12.5
1 HDFCBANK.NS 18.1 Financial Services 15.2
Potential Improvements:
Handle More Tickers: If you want to analyze all NSE stocks, you'd need a full list (e.g., from an API or database). This could be added as an input.
Error Handling: The code includes basic error handling, but you might want to add retries for network issues.
Data Accuracy: Yahoo Finance data is delayed and not always perfect. For real-time or official data, consider NSE's API (if available) or paid services like Alpha Vantage.
Performance: If the list is large, this could take time. Use time.sleep(1) between requests to avoid rate limits.
Customization: You can modify the revenue growth threshold or use forward PE instead of trailing PE.
Run this code in a Python environment, and ensure you have the necessary libraries installed. If you encounter any issues, feel free to provide more details!