Why Python Is the Investor’s Best New Tool
You don’t need a quantitative finance degree to build a Python stock screener for investors. A working screener — one that automatically filters stocks by the metrics you care about — takes under 30 lines of code using freely available libraries. This tutorial walks you through exactly that, including the full working code you can run today.
What You’ll Build
A Python script that:
- Downloads financial data for a list of tickers using
yfinance - Filters by P/E ratio, revenue growth, and debt-to-equity
- Outputs a ranked shortlist of qualifying stocks
Prerequisites
Install the required libraries:
pip install yfinance pandas
💡 Setup Note: Requires Python 3.8 or higher. No API key or paid account needed — yfinance pulls free data directly from Yahoo Finance. If you see rate-limiting errors on large universes, add a short time.sleep(0.5) between ticker fetches.
The Screener Code
import yfinance as yf
import pandas as pd
# Define your universe of stocks to screen
tickers = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'META', 'NVDA', 'TSLA',
'JPM', 'JNJ', 'PG', 'KO', 'V', 'MA', 'HD', 'UNH']
# Define your screening criteria
MAX_PE = 30
MIN_REVENUE_GROWTH = 0.10 # 10% YoY revenue growth
MAX_DEBT_TO_EQUITY = 1.5
results = []
for ticker in tickers:
try:
stock = yf.Ticker(ticker)
info = stock.info
pe = info.get('forwardPE', None)
rev_growth = info.get('revenueGrowth', None)
de_ratio = info.get('debtToEquity', None)
name = info.get('shortName', ticker)
sector = info.get('sector', 'N/A')
if pe and rev_growth and de_ratio:
if pe < MAX_PE and rev_growth > MIN_REVENUE_GROWTH and de_ratio < MAX_DEBT_TO_EQUITY * 100:
results.append({
'Ticker': ticker,
'Name': name,
'Sector': sector,
'Forward P/E': round(pe, 2),
'Revenue Growth': f"{rev_growth*100:.1f}%",
'D/E Ratio': round(de_ratio/100, 2)
})
except Exception as e:
print(f"Error fetching {ticker}: {e}")
df = pd.DataFrame(results).sort_values('Forward P/E')
print(df.to_string(index=False))
📈 Reading the Output: The screener outputs stocks sorted by Forward P/E (lowest first). The lowest P/E stocks on the list are the most “value-priced” among those passing your growth and leverage filters — a natural starting point for deeper research. Don’t stop here; this is a shortlist, not a buy signal.
Understanding the Code
- Universe definition: Supply the tickers to screen. For a broader screen, import an S&P 500 list from Wikipedia using
pd.read_html() - yfinance data: The
infodict contains hundreds of fundamental fields — useprint(stock.info.keys())to explore - Filtering logic: Simple conditional — only stocks meeting all three criteria pass through
- Output: A pandas DataFrame sorted by Forward P/E, easily exported with
df.to_csv('results.csv')
Customizing Your Screener
Additional fields to screen on:
info.get('returnOnEquity')— return on equityinfo.get('freeCashflow')— free cash flowinfo.get('grossMargins')— gross margin %info.get('dividendYield')— dividend yieldinfo.get('marketCap')— filter by market cap tier
For a dividend-focused screen, pair this with the criteria from our guide on how to pick high-dividend stocks.
Adding Technical Filters
Extend the screener to include technical analysis criteria — for example, only stocks trading above their 200-day moving average:
hist = stock.history(period="1y")
ma200 = hist['Close'].mean()
current_price = hist['Close'].iloc[-1]
above_ma200 = current_price > ma200
Combining fundamental screening with basic technical filters gives you a powerful two-stage process: find quality businesses, then time the entry. For a deeper understanding of technical signals, see our guide on how to perform technical analysis on stocks.
⚠️ Important Caveat: yfinance data has occasional gaps and inaccuracies — field availability varies by ticker and region, and values can lag official filings. Always verify key metrics against SEC filings or earnings reports before acting. This screener surfaces candidates; it does not replace fundamental research.
Important Caveats
- yfinance data has occasional gaps and inaccuracies — verify key metrics against SEC filings before acting
- This is a screening tool, not a buy signal — every candidate still requires fundamental research
- Financial ratios should be interpreted in sector context — a P/E of 25 is cheap for software, expensive for utilities
Conclusion
A 30-line Python stock screener for investors lets you systematically filter a large universe down to a manageable shortlist in seconds. Combined with the reinforcement learning techniques covered in our deep RL asset allocation guide, Python skills open the door to a full quantitative research workflow.
More in the AI Investing Series
- How to Use AI Tools to Screen Stocks in 2025
- The Best AI Investing Tools of 2025 (Free and Paid)
- LLM-Based Earnings Analysis: How to Summarize 10-Ks with AI
- How Hedge Funds Use Machine Learning: What Retail Investors Can Learn
Get more investor-focused Python tutorials. Subscribe to Market Digests.
