← All posts

How to Build a Stock Screener in Python With an API

Build a stock screener in Python with an API. One request returns the index roster, prices come in batches, pandas filters. A Dow 30 screen costs 31 requests.

Building a stock screener in Python takes three steps. Fetch the list of candidate companies, pull the numbers for every one of them in as few requests as possible, then filter and sort the result in pandas. With xfinlink the candidate list is a single request to the index endpoint, the prices endpoint accepts up to 100 tickers per request on the Pro plan, and the screen itself is ordinary DataFrame code. Each ticker counts as one request against the daily quota, so a year of daily prices for the 30 members of the Dow Jones Industrial Average costs 31 requests, and the same pass over the S&P 500 costs about 504, roughly 5% of a Pro day.

What does a stock screener need before any code runs?

A screen asks a cross-sectional question, one date and many companies, and two choices shape the answer before the first filter is written. One is the universe, the set of companies allowed to pass. The other is the date the numbers describe.

Index membership is the usual universe, and it has to come from the index as it stood on the date being screened. Today’s S&P 500 list holds the companies that survived to today, so a screen of 2015 run over it has already removed every later bankruptcy, buyout and demotion. The mechanism, and how much it inflates results, is the subject of survivorship bias in backtesting. For a screen of the present the problem does not arise, but the same code should work for a past date without changes, and that depends on the data source more than on the code.

How do you get the list of stocks to screen?

One request returns a whole roster. xfl.index("djia") returns the current members of the Dow Jones Industrial Average, and "sp500" and "ndx100" return the S&P 500 and the Nasdaq-100. Passing as_of="2015-06-30" returns the members on that date instead, including the ones later removed, acquired or delisted. A page holds up to 1,000 rows, so the S&P 500 arrives in one response, and the request counts once whatever the roster size. The index membership reference lists the fields.

Each roster row carries a ticker and an entity_id. On these rows the id names one share class, and the prices endpoint accepts it directly. The metrics endpoint identifies companies rather than share classes, so a valuation screen sends it the roster’s tickers.

How many requests does a screen cost?

Three rules from the rate limits page set the bill. Each ticker or entity_id in a request counts as one request against the daily quota. A roster, which names no ticker, counts as one. Each page of a paged result counts again, so a 100-ticker request that runs to three pages counts 300.

The third rule is the one that can double the cost of a screen. A prices page holds up to 5,000 rows and a metrics page up to 100, so the cheapest request is one sized to fit a single page. A year of daily prices is about 252 rows per ticker, which means 19 tickers fill one prices page. Sending 30 tickers in one request would return 7,560 rows over two pages and count 60. Sending them as 19 and 11 counts 30.

Plan Tickers per request Requests per day Dow 30, a year of daily prices S&P 500, a year of daily prices
Free 1 100, and 40 an hour 31 requests, inside one hour 504 requests, about six days of quota
Pro 100 10,000 31 requests in 3 calls 504 requests in 28 calls, about 127,000 rows
Max 500 50,000 31 requests in 3 calls 504 requests in 28 calls

The S&P 500 column assumes 503 tickers in batches of 19, plus the roster. A one-day snapshot of the same 503 names from the metrics endpoint also counts 504, because request units follow tickers rather than rows. On Pro, 504 is about 5% of the day, which leaves room to rerun a screen many times while the rules are still changing. Plan limits are as published in November 2026 on the pricing page.

A working screen of Dow 30 large caps near their highs

The rules here are deliberately plain. Keep members with a market cap above $200 billion whose split-adjusted close is within 10% of its 52-week high. Market cap comes with each price row, in whole dollars for that share class, and the high is the maximum adjusted close over the year.

import pandas as pd
import xfinlink as xfl

xfl.set_api_key("YOUR_API_KEY")  # free at https://xfinlink.com/signup

members = xfl.index("djia")                       # the roster, 1 request
tickers = members["ticker"].tolist()

batch = 5000 // 252   # a year of daily rows for 19 tickers fills one page
frames = [xfl.prices(tickers[i:i + batch], start="2025-11-13", end="2026-11-13",
                     fields=["close", "adj_close", "market_cap"])
          for i in range(0, len(tickers), batch)]
px = pd.concat(frames)

latest = px[px["date"] == px["date"].max()].set_index("ticker")
latest["off_high"] = latest["adj_close"] / px.groupby("ticker")["adj_close"].max() - 1
latest["cap_bn"] = latest["market_cap"] / 1e9

screen = latest[(latest["cap_bn"] > 200) & (latest["off_high"] > -0.10)]
print(f"{len(members)} members, {len(frames)} price requests, {len(px):,} rows")
print(screen.sort_values("cap_bn", ascending=False)[["close", "cap_bn", "off_high"]].round(3).to_string())

Output:

30 members, 2 price requests, 7,560 rows
         close    cap_bn  off_high
ticker                            
AAPL    356.27  5177.380     0.000
MSFT    523.88  3890.435    -0.057
AMZN    266.66  2883.431    -0.061
WMT     128.09  1016.234    -0.046
JPM     346.19   919.345    -0.052
V       425.76   734.212    -0.025
JNJ     285.75   687.889     0.000
CVX     219.89   432.177    -0.066
KO       99.25   426.964     0.000
PG      169.80   393.560     0.000
UNH     407.46   365.093    -0.066
MRK     147.76   364.265    -0.056
AMGN    465.67   251.886    -0.027
DIS     118.97   205.424    -0.006

Fourteen of the 30 members passed on 13 November 2026, and four of them (Apple, Johnson & Johnson, Coca-Cola and Procter & Gamble) closed at their 52-week high that day. The whole run used 31 requests, one for the roster and one per ticker across two price calls of 19 and 11.

Two column choices carry the result. The high is measured on adj_close because a stock split cuts the traded close overnight, and a raw maximum would read every recent split as a fall from the high. The printed close is the price as traded, which is what the market cap multiplies. On the Free plan the same code runs with batch = 1, making 30 price calls plus the roster, 31 in all, inside Free’s 40 requests an hour, and the year of history starts one year before the day the request is sent.

How do you add P/E and other valuation filters?

Valuation and profitability columns come from the metrics endpoint, documented in the metrics reference. It returns fields such as pe_ratio, ps_ratio, pb_ratio and market_cap for up to 100 tickers per request on paid plans over a date range of a year or less, computed from SEC filings and daily prices, and the period parameter selects annual, quarterly, trailing-twelve-month or daily rows. Two details differ from prices. A metrics page holds at most 100 rows and the default page is 20, so a REST call for 100 tickers should send limit=100 or it will run to five pages and count five times. The Python client sets the page size itself. Metrics also reports market_cap for the whole company, summing every listed share class, in millions of US dollars, while price rows give one share class in whole dollars, so a filter copied from one to the other is off by a factor of a million.

A past-date screen uses the same calls with dates attached. The roster takes as_of, prices take end, and metrics take as_of as a knowledge date, which returns the statements as filed by that day rather than later restatements.

Which plan does an index-sized screen need?

The Dow 30 screen runs on Free, which suits learning the method and testing rules on a small universe. A daily S&P 500 or Nasdaq-100 screen wants Pro, where a full pass is a few percent of the day and history reaches back to 1962 for prices. Max raises the per-request cap to 500 tickers and the day to 50,000 requests, which matters for universes in the thousands or for many reruns a day. The way per-ticker counting compares across providers is set out in the guide to financial data API rate limits, and the questions to ask of any API before building a screen on it are in what API to use for a stock screener.

Licensing follows who sees the output. A screen for one person’s own research fits Pro, and if people outside the company see the data, for example in a screener built into a public website, that use needs the Redistribution plan. For a quick look at current values without writing code, the free stock screener filters US-listed stocks, ADRs and ETFs in the browser.

FAQ

Can this screen run on the free plan?
Yes, for the Dow 30. With batch = 1 it makes 31 requests, inside the Free plan’s 40 an hour and 100 a day. An S&P 500 pass at one request per ticker needs about six days of Free quota.

Why fetch prices for the whole year instead of one day?
The 52-week high needs the whole year. A screen that only filters on market cap or P/E needs one day, and setting start and end to the same date returns one row per ticker at the same request cost.

How does a historical screen stay free of survivorship bias?
Take the universe from xfl.index(..., as_of=date) for each screening date rather than from today’s roster, and key every join on entity_id, which stays with the security when its ticker changes.

Built with xfinlink — free financial data API for Python.