CodeForFinance
Python

Build a Stock Screener in Python

A stock screener lets you filter thousands of stocks down to a shortlist that matches your criteria. Instead of paying for expensive screener subscriptions, you can build your own in Python that does exactly what you want. In this tutorial, we build a fully functional stock screener that filters by P/E ratio, market cap, and dividend yield using free API data.

Prerequisites

  • Basic Python (variables, loops, functions)
  • pip installed
  • Free Alpha Vantage API key

Step 1.Install dependencies

We need requests for API calls and pandas for data manipulation.

pip install requests pandas

Step 2.Set up the API connection

Alpha Vantage provides free fundamental data. The OVERVIEW endpoint gives us P/E, market cap, dividend yield and more.

import requests
import pandas as pd

API_KEY = "YOUR_ALPHA_VANTAGE_KEY"
BASE_URL = "https://www.alphavantage.co/query"

def get_overview(symbol: str) -> dict:
    params = {
        "function": "OVERVIEW",
        "symbol": symbol,
        "apikey": API_KEY
    }
    r = requests.get(BASE_URL, params=params)
    return r.json()

Step 3.Define your screening criteria

Define clear thresholds. The function returns True only if a stock meets all criteria.

CRITERIA = {
    "pe_max": 20,
    "market_cap_min": 1_000_000_000,  # $1B+
    "dividend_yield_min": 0.02,       # 2%+
}

def passes_screen(data: dict) -> bool:
    try:
        pe = float(data.get("PERatio", 999))
        cap = float(data.get("MarketCapitalization", 0))
        div_yield = float(data.get("DividendYield", 0))
        return (
            pe <= CRITERIA["pe_max"]
            and cap >= CRITERIA["market_cap_min"]
            and div_yield >= CRITERIA["dividend_yield_min"]
        )
    except (ValueError, TypeError):
        return False

Step 4.Screen a list of tickers

Loop through your watchlist, check each stock against the criteria, and collect the ones that pass.

WATCHLIST = ["AAPL", "MSFT", "JNJ", "XOM", "PG", "KO", "PFE", "VZ", "T", "INTC"]

results = []
for ticker in WATCHLIST:
    data = get_overview(ticker)
    if passes_screen(data):
        results.append({
            "Symbol": ticker,
            "Name": data.get("Name"),
            "PE": data.get("PERatio"),
            "MarketCap": data.get("MarketCapitalization"),
            "DividendYield": data.get("DividendYield"),
        })

df = pd.DataFrame(results)
print(df.to_string(index=False))

Step 5.Export results to CSV

Save results for further analysis or to track over time.

df.to_csv("screener_results.csv", index=False)
print(f"Found {len(df)} stocks matching criteria")

Expected Output

  Symbol                 Name    PE  MarketCap DividendYield
     VZ  Verizon Communications  8.92  168000000000        0.0678
      T               AT&T Inc  7.45  139000000000        0.0582

Next Steps

  • Add technical indicators (RSI, moving averages) to your screener
  • Schedule automatic daily runs with cron
  • Build a web dashboard with Streamlit

Recommended Reading

Python for Finance

As an Amazon Associate we may earn from qualifying purchases.

Browse All Tutorials →

Developer Essentials

As an Amazon Associate we may earn from qualifying purchases.