A stock screener is a funnel you write down: a universe, some rules, a ranking. Its value is that it runs the same way every day and leaves a record of what your rules said. Its limit is that it only sorts the data you give it. This page shows how to build one in Python, how to check the maths by hand, and which mistakes make screens look better than they are.
Step 1: compute the metrics as small, testable functions
Each metric should be a function you can check on paper. Here is RSI, the least obvious one:
def rsi(c, n=14):
if len(c) < n + 1:
return None
ch = [b - a for a, b in zip(c, c[1:])]
g = [max(x, 0.0) for x in ch]; l = [max(-x, 0.0) for x in ch]
ag, al = sum(g[:n]) / n, sum(l[:n]) / n
for gi, li in zip(g[n:], l[n:]):
ag = (ag * (n - 1) + gi) / n; al = (al * (n - 1) + li) / n
if al == 0:
return 100.0 if ag > 0 else 50.0
return 100.0 - 100.0 / (1.0 + ag / al)
Check it with numbers small enough to do by hand. With n = 3 and closes 10, 11, 10, 12, 13, 12 the changes are +1, -1, +2, +1, -1.
- Seed: average gain (1 + 0 + 2) / 3 = 1, average loss (0 + 1 + 0) / 3 = 1/3.
- After +1: gain (1 x 2 + 1) / 3 = 1, loss (1/3 x 2 + 0) / 3 = 2/9.
- After -1: gain (1 x 2 + 0) / 3 = 2/3, loss (2/9 x 2 + 1) / 3 = 13/27.
- RS = (2/3) / (13/27) = 18/13, so RSI = 100 - 100 / (1 + 18/13) = 58.06.
Put that in a test. If your function prints something else, the function is wrong, not the arithmetic.
Step 2: add momentum and a trend check
12-1 momentum is the return from the close 274 sessions back to the close 22 sessions back: close[-22] / close[-274] - 1. Pair it with a simple trend description such as the latest close against its 50-day average. A rule like "RSI at or below 70, momentum at or above 0, close above the 50-day average" is a placeholder to show the mechanics, not a recommendation.
Step 3: add fundamentals carefully
Earnings yield is EBIT divided by enterprise value: with invented numbers, EBIT 120 on enterprise value 1,500 is 8.0%. Free cash flow yield is free cash flow over market cap. The Piotroski F-score is nine yes or no signals, such as whether return on assets rose and whether the share count stayed flat. Two rules keep this honest: a missing number must fail a filter rather than pass it, and a ticker missing a ranked metric must be left out rather than scored on partial data.
Step 4: rank with percentiles, not raw values
Raw values cannot be averaged across metrics because the scales differ. Convert each metric to a percentile rank from 0 to 1, flip it where lower is better (volatility), and take a weighted average. Ties share the average rank, so values 1, 1, 3 rank 0.25, 0.25, 1.0. The score is for sorting, not a measure of quality.
Step 5: run it daily and check the data first
A scheduled screen on bad data produces confident nonsense. Before each run, check for too little history, non-positive prices, stale last dates and one-day moves above 50%, which are usually unadjusted splits. In a scheduled job, stop on any problem rather than writing output. Keep every dated output: it is how you later check whether your rules did anything.
The mistakes that make screens look better than they are
- Survivorship bias. If delisted companies are missing from the data, old results look better than they were.
- Look-ahead bias. Use a figure from the date it was published, not the date of the period it covers.
- Over-tuning. Choose thresholds before you look, and keep a period you never tuned on.
- Counting only your best run. Try 50 variations and one looks good by luck. Count your tries.
- Costs and taxes. A ranking ignores them. A fair test does not.
What a screen should be used for
As a to-do list for your own research. For each name, read the filings and decide for yourself whether anything is worth acting on. Many names will not survive that reading, which is the point of doing it. Decisions about your money belong with you and a qualified, licensed professional who knows your circumstances.
What the full kit adds
The code above covers moving average, RSI and 12-1 momentum with pass or fail thresholds you set. The full kit adds the valuation and quality metrics, the config-driven engine, data checks, dated reports with a diff against the last run, a daily scheduler, synthetic sample data (no real tickers), 28 tests with hand-computed expected values, and written chapters on each topic. It contains no stock picks and no data.
Stock screener kit
The full pack is available. Get the stock screener kit. This guide stands on its own without it.
Frequently asked questions
How do I build a stock screener in Python?
Load adjusted prices from a CSV, compute each metric as a small function, apply your filters, and write the result to a dated file. A funnel of universe rules, filters and a weighted ranking is enough. The code on this page does it in standard-library Python, and the full kit adds fundamentals, data checks, reports and a scheduler.
How is RSI calculated?
Take daily price changes. Average the gains and the losses over the first 14 days, then smooth each as (previous average x 13 + today's value) / 14. RS is the average gain divided by the average loss, and RSI = 100 - 100 / (1 + RS). With closes 10, 11, 10, 12, 13, 12 and n = 3 the result is 58.06.
What is 12-1 momentum?
It is the return from about 13 months ago to about one month ago, skipping the most recent month. In code with daily closes it is close[-22] / close[-274] - 1. The skipped month is a common convention to keep very recent moves out of the measure.
What is the Piotroski F-score?
A nine-point checklist of yes or no signals about profitability, leverage and efficiency, published by accounting professor Joseph Piotroski in 2000. Each signal that is true adds one point. Higher scores mean more signals were true, nothing more.
Can a screener tell me what to buy?
No. A screener sorts data you supply using rules you choose. It cannot see why a number looks the way it does and it does not know your circumstances. Treat its output as a list of names to research yourself. This page and the kit are for education, not investment advice.
Why do backtests of screens mislead?
Common causes are survivorship bias (delisted companies missing from the data), look-ahead bias (using a figure before it was published), over-tuning thresholds to the past, and ignoring costs and taxes. Fix the rules before you look, keep a period you never tuned on, and count how many variants you tried.
