Python Tutorial
Build a Stock Screener in Python
Filter UK stocks by P/E ratio, dividend yield, and market cap — all in Python.
Prerequisites
Basic Python knowledge. Familiarity with pandas DataFrames.
Install Dependencies
pip install yfinance pandasFetch Stock Data
We'll screen 10 FTSE 100 stocks, pulling key metrics from Yahoo Finance:
import yfinance as yf
import pandas as pd
# Define a list of UK stocks to screen
tickers = ["SHEL.L", "AZN.L", "HSBA.L", "BP.L", "GSK.L",
"RIO.L", "ULVR.L", "DGE.L", "LLOY.L", "VOD.L"]
results = []
for ticker in tickers:
try:
stock = yf.Ticker(ticker)
info = stock.info
results.append({
"Ticker": ticker,
"Name": info.get("shortName", "N/A"),
"Price": info.get("currentPrice", 0),
"PE Ratio": info.get("trailingPE", None),
"Market Cap (B)": round(info.get("marketCap", 0) / 1e9, 1),
"Dividend Yield %": round((info.get("dividendYield", 0) or 0) * 100, 2),
})
except:
pass
df = pd.DataFrame(results)
print(df.to_string(index=False))Apply Filters
Now screen for value stocks — low P/E ratio and high dividend yield:
# Filter: PE < 15 and Dividend Yield > 3%
screened = df[(df["PE Ratio"] < 15) & (df["Dividend Yield %"] > 3)]
print("\nScreened Results (PE < 15, Div > 3%):")
print(screened.to_string(index=False))Rank Results
# Sort by dividend yield descending
ranked = df.sort_values("Dividend Yield %", ascending=False)
print("\nRanked by Dividend Yield:")
print(ranked.to_string(index=False))Next Steps
- Add more tickers — screen the entire FTSE 350
- Add technical filters — RSI, moving averages
- Schedule daily scans with a cron job
- Export results to CSV or email alerts