yfscreen: Yahoo Finance Screener in R and Python

    Date:

    Open Source Quantitative Finance 2025

    Overview

    yfscreen is a package that provides simple and efficient access to Yahoo Finance’s screener API (https://finance.yahoo.com/research-hub/screener/) for querying and retrieval of financial data.

    The core functionality of the yfscreen package abstracts the complexities of interacting with Yahoo Finance APIs, such as session management, crumb and cookie handling, query construction, pagination, and JSON payload generation. This abstraction allows users to focus on filtering and retrieving data rather than managing API details. Use cases include screens across a range of security types:

    • Equities: coverage spans 50 regions to enable the identification of top-performing stocks based on specified criteria
    • Mutual funds: funds can be screened using metrics such as historical performance, performance ratings, and other factors
    • ETFs: a wide range of ETFs can be filtered by criteria including expense ratio, historical performance, and additional attributes
    • Indices: stock market indices are available and often categorized by sector, industry, or the overall market
    • Futures: futures contracts can be screened by exchange, price percent changes, and regional specifications

    The package supports advanced query capabilities, including logical operators, nested filters, and customizable payloads. It automatically handles pagination for efficient retrieval of large datasets by fetching results in batches of up to 250 entries per request. Filters can be dynamically defined to accommodate a wide range of screen needs.

    The implementation leverages standard HTTP libraries to handle API interactions efficiently and provides support for both R and Python to make it accessible for a broad audience.

    Installation in R

    • Install the released version from CRAN:
    install.packages("yfscreen")
    • Or the development version from GitHub:
    # install.packages("devtools")
    devtools::install_github("jasonjfoster/screen/r")
    • Then load the package:
    library(yfscreen)

    Installation in Python

    • Install the released version from PyPI:
    pip install yfscreen
    • Or the development version from GitHub:
    pip install 
      git+https://github.com/jasonjfoster/screen.git@main#subdirectory=python
    • Then import the package:
    import yfscreen as yfs

    Available filters

    Load the package and explore the available filter options using yfscreen::data_filters in R or yfs.data_filters in Python:

    Security types Data types Field names
    equity Market Data eodprice
    mutualfund Ratios exchange
    etf Performance intradayprice
    index
    future Technicals ticker

    Usage

    Create query

    The yfs::create_query function in R and yfs.create_query method in Python create a structured query with logical operations and nested conditions formatted for the Yahoo Finance API.

    Parameters

    • filters: list. Each element is a sublist that defines a filtering condition with the following structure:
      • comparison: string. Comparison operator (i.e., “gt”, “lt”, “eq”, “btwn”).
      • field: list. Field name (e.g. “region”) and its associated value(s).
    • top_operator: string. Top-level logical operator to combine all filters (i.e., “and”, “or”).

    Value

    A nested list representing the structured query with logical operations and nested conditions formatted for the Yahoo Finance API.

    Examples

    • Most active stocks: discover the most traded equities in the trading day.

    R

    most_actives <- list(
      list("eq", list("region", "us")),
      list("btwn", list("intradaymarketcap", 2e9, 1e11)),
      list("gt", list("dayvolume", 5e6))
    )
    query <- yfscreen::create_query(most_actives)

    Python

    most_actives = [
      ["eq", ["region", "us"]],
      ["btwn", ["intradaymarketcap", 2e9, 1e11]],
      ["gt", ["dayvolume", 5e6]]
    ]
    query = yfs.create_query(most_actives)

    Get data

    The yfs::get_data function in R and yfs.get_data method in Python get data from the Yahoo Finance API using the specified payload.

    Parameters

    • payload: list. Payload that contains search criteria created using create_query() and create_payload().

    Value

    A data frame that contains data from the Yahoo Finance API for the specified search criteria.

    Examples

    R

    payload <- yfscreen::create_payload("equity", query)
    data <- yfscreen::get_data(payload)

    Python

    payload = yfs.create_payload("equity", query)
    data = yfs.get_data(payload)

    View data

    R

    head(data[ , c("symbol", "regularMarketPrice.raw",
                   "regularMarketChangePercent.raw", ...)])

    Python

    data[["symbol", "regularMarketPrice.raw",
          "regularMarketChangePercent.raw", ...]].head()
    symbol price chg (%) vol (m) mkt cap (b)
    AAPL 208.27 1.79% 28.10 3,128.65
    MSFT 388.00 3.64% 13.01 2,884.38
    NVDA 106.26 3.46% 177.99 2,592.74
    GOOG 161.22 2.22% 17.21 1,949.05
    AMZN 186.41 3.22% 31.64 1,978.26

    More filters in R

    • Undervalued growth stocks: equities with earnings growth above 25% and relatively low P/E and PEG ratios.
    sec_type <- "equity"
    undervalued_growth_stocks <- list(
      list("btwn", list("peratio.lasttwelvemonths", 0, 20)),
      list("lt", list("pegratio_5y", 1)),
      list("gt", list("epsgrowth.lasttwelvemonths", 25))
    )
    • Top mutual funds: mutual funds with a performance rating of 4 or 5.
    sec_type <- "mutualfund"
    top_mutual_funds <- list(
      list("gt", list("intradayprice", 15)),
      list("eq", list("performanceratingoverall", 4)),
      list("eq", list("performanceratingoverall", 5))
    )

    More filters in Python

    • Day gainer stocks: equities with the largest gains during the trading day.
    sec_type = "equity"
    day_gainers = [
      ["gt", ["percentchange", 3]],
      ["gt", ["intradaymarketcap", 2e9]],
      ["gt", ["intradayprice", 5]],
      ["gt", ["dayvolume", 1.5e3]]
    ]
    • Day loser stocks: equities with the largest losses during the trading day.
    day_losers = [
      ["lt", ["percentchange", -2.5]],
      ["gt", ["intradaymarketcap", 2e9]],
      ["gt", ["intradayprice", 5]],
      ["gt", ["dayvolume", 2e3]]
    ]

    Application

    Next we use the yfscreen package to analyze how positioning influenced recent performance among “Tactical Allocation” mutual funds with the “categoryname” field to define the peer group. To estimate asset allocations, we use a constrained least squares regression with two explanatory variables: the S&P 500 Index (SP500) to represent market exposure and the 3-month Treasury bill rate (DTB3) to represent cash. The objective is to estimate how each mutual fund allocates between market and cash exposures subject to the following constraints:

    The sum-to-one constraint ensures that the entire portfolio is allocated between market and cash positions without leverage. The positive bounds reflect the typical long-only structure of mutual funds.

    Results

    After the estimation of market and cash exposures, we separate mutual funds into performance quartiles and compare positioning over time. The chart below shows the regression-based market and cash split for the top (Q1) and bottom (Q4) performing “Tactical Allocation” managers since the U.S. election in November 2024. The analysis provides insight into how tactical shifts, such as increasing cash allocations or maintaining higher market exposure, contributed to differences in recent mutual fund performance.

    library yfscreen chart

    Data source: Federal Reserve Economic Data (FRED): https://fred.stlouisfed.org/; Yahoo Finance API: https://finance.yahoo.com/

    The results show that Q1 managers shifted allocations into cash at the end of February and de-risked ahead of subsequent market volatility. In contrast, Q4 managers maintained higher market exposure that contributed to underperformance over the same period. By comparing estimated exposures across quartiles, the analysis provides a regression-based approach for understanding how tactical allocation decisions, specifically the market versus cash split, affected recent performance.

    Conclusion

    The yfscreen package provides simple and efficient access to Yahoo Finance’s screener API for querying and retrieving financial data. It abstracts the complexities of session management, query construction, pagination, and payload generation. This allows users to focus on filtering and retrieving data across a range of security types, including equities, mutual funds, ETFs, indices, and futures. The package supports advanced query capabilities, such as logical operators, nested filters, and customizable payloads, and automatically handles pagination to retrieve large datasets efficiently. It is available for both R and Python to make it accessible for a broad audience. The analysis of tactical allocation mutual funds illustrates how the package can be used to estimate asset exposures and interpret positioning differences across managers. For more examples and analysis in R and Python, go to https://jasonjfoster.github.io/.

    Disclosure: Interactive Brokers Third Party

    Information posted on IBKR Campus that is provided by third-parties does NOT constitute a recommendation that you should contract for the services of that third party. Third-party participants who contribute to IBKR Campus are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

    This material is from Jason Foster and is being posted with its permission. The views expressed in this material are solely those of the author and/or Jason Foster and Interactive Brokers is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to buy or sell any security. It should not be construed as research or investment advice or a recommendation to buy, sell or hold any security or commodity. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

    Disclosure: ETFs

    Any discussion or mention of an ETF is not to be construed as recommendation, promotion or solicitation. All investors should review and consider associated investment risks, charges and expenses of the investment company or fund prior to investing. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

    Disclosure: Mutual Funds

    Mutual Funds are investments that pool the funds of investors to purchase a range of securities to meet specified objectives, such as growth, income or both. Investors are reminded to consider the various objectives, fees, and other risks associated with investing in Mutual Funds. Please read the prospectus accordingly. This communication is not to be construed as a recommendation, solicitation or promotion of any specific fund, or family of funds. Interactive Brokers may receive compensation from fund companies in connection with purchases and holdings of mutual fund shares. Such compensation is paid out of the funds’ assets. However, IBKR does not solicit you to invest in specific funds and does not recommend specific funds or any other products to you. For additional information please visit https://www.interactivebrokers.com/en/index.php?f=1563&p=mf

    Disclosure: Futures Trading

    Futures are not suitable for all investors. The amount you may lose may be greater than your initial investment. Before trading futures, please read the CFTC Risk Disclosure. A copy and additional information are available at ibkr.com.

    Go Source

    Chart

    SignUp For Breaking Alerts

    New Graphic

    We respect your email privacy

    Share post:

    Popular

    More like this
    Related

    Are Traders Just Numb Now?

    To watch this video you must accept functional cookies. Manage...

    Pricier Used Cars Temper Trade Optimism: May 7, 2025

    Trading action has been indecisive this morning as participants...

    Forecast Contracts: Initial Claims Are Trending Higher: May 7, 2025

    Your Privacy When you visit any website it may use...

    Trump Trade: Treasury’s Bessent, USTR Greer to meet with China

    U.K. reportedly near trade pact with U.S. with breaks...