Saturday, March 28, 2026
HomeInvestment StrategyAnalysisPython for Investors: Build a Simple Stock Screener in 30 Lines

Python for Investors: Build a Simple Stock Screener in 30 Lines

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:

  1. Downloads financial data for a list of tickers using yfinance
  2. Filters by P/E ratio, revenue growth, and debt-to-equity
  3. 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 info dict contains hundreds of fundamental fields — use print(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 equity
  • info.get('freeCashflow') — free cash flow
  • info.get('grossMargins') — gross margin %
  • info.get('dividendYield') — dividend yield
  • info.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

Get more investor-focused Python tutorials. Subscribe to Market Digests.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here