Skip to main content

portfolios.filter_sorting_data()

Filter sorting data.

Usage

Source

portfolios.filter_sorting_data(
    data,
    filter_options=None,
    data_options=None,
    rebalancing_month=None,
    quiet=False
)

Applies sample construction filters to a data frame before portfolio sorting. Filters are applied in a fixed order: financials exclusion, utilities exclusion, minimum stock price, minimum size quantile, minimum listing age, positive book equity, and positive earnings. An informational warning is emitted for each filter that actually removes at least one observation.

Without ‘rebalancing_month’, every month is a formation month and each row is screened on its own values. The screens are then free of look-ahead bias only if the screened columns are known at the start of the month: the default price column ‘prc_lag’ and ‘mktcap_lag’ are lagged by one month, and accounting variables such as book equity and earnings should be lagged as well (e.g., with ‘join_lagged_values’).

With ‘rebalancing_month’, portfolios are formed once a year and held for twelve months. By default (‘filter_options(timing=“formation”)’), each screen is evaluated in the formation month only, and a stock that passes all screens keeps all its rows until the next formation month, even if it fails a screen in a holding month. Rows of stocks that fail a screen at formation, and rows before the first formation month, are removed. With ‘timing=“every_period”’, the screens are evaluated in every month (ex-post) and a warning is issued, because dropping holding-month returns based on information from those months can bias factor returns.

Parameters

data: pl.DataFrame

Data frame containing the stock-level panel data to be filtered.

filter_options: dict = None

Dict produced by ‘filter_options’. If None (the default), the defaults from ‘filter_options’ are used (i.e., no filters are applied). The accepted entries include:

  • ‘exclude_financials’ (bool): Whether to exclude financial firms (SIC codes 6000 to 6799). Defaults to False.
  • ‘exclude_utilities’ (bool): Whether to exclude utility firms (SIC codes 4900 to 4999). Defaults to False.
  • ‘min_stock_price’ (float, optional): Minimum stock price required to include an observation. None (the default) applies no price filter.
  • ‘min_size_quantile’ (float, optional): Minimum cross-sectional size quantile (based on lagged market cap) required to include an observation. None (the default) applies no size quantile filter. The cutoff is computed from NYSE stocks only; the ‘exchange’ column (mapped via ‘data_options’) must be present or a ValueError is raised.
  • ‘min_listing_age’ (float, optional): Minimum number of months a stock must have been listed in CRSP. None (the default) applies no listing age filter.
  • ‘exclude_negative_book_equity’ (bool): Whether to exclude observations with non-positive book equity. Defaults to False.
  • ‘exclude_negative_earnings’ (bool): Whether to exclude observations with non-positive earnings. Defaults to False.
  • ‘timing’ (str): Either ‘formation’ (the default) to apply the screens only in the formation month when portfolios are rebalanced once a year, or ‘every_period’ to apply them in every month, which can introduce look-ahead bias.
data_options: dict = None

Column-name mapping (see ‘data_options’). The ‘siccd’ element specifies the SIC code column, ‘price’ specifies the price column of the ‘min_stock_price’ screen, ‘mktcap_lag’ specifies the market capitalization column, ‘date’ specifies the date column, ‘listing_age’ specifies the listing age column, ‘be’ specifies the book equity column, and ‘earnings’ specifies the earnings column. With ‘rebalancing_month’, the ‘id’ element (default ‘permno’) is used to keep a stock across its holding period. Uses the ‘data_options’ defaults when None.

rebalancing_month: int = None

Month (1 to 12) in which portfolios are formed when they are rebalanced once a year (see ‘compute_portfolio_returns’). None (the default) means monthly rebalancing. Together with the ‘timing’ element of ‘filter_options’, it determines when the screens apply.

quiet: bool = False
Whether informational messages should be suppressed.

Returns

pl.DataFrame
Filtered data frame, preserving the class and structure of the input.

Examples

import datetime as dt
import polars as pl
from tidyfinance import filter_sorting_data, filter_options
data = pl.DataFrame({
    'permno': range(1, 6),
    'date': [dt.date(2020, 1, 1)] * 5,
    'siccd': [6100, 2000, 4950, 3000, 6500],
    'prc_lag':[5.0, 0.5, 15.0, 20.0, 10.0],
})
filter_sorting_data(
    data,
    filter_options=filter_options(
        exclude_financials=True,
        min_stock_price=1,
    ),
)
# Annual rebalancing in July: the price screen is evaluated in July
# only, so stock 1 is kept in August although its price falls below 1
data_annual = pl.DataFrame({
    'permno': [1, 1, 2, 2],
    'date': [dt.date(2020, 7, 1), dt.date(2020, 8, 1)] * 2,
    'prc_lag': [2.0, 0.5, 0.5, 2.0],
})
filter_sorting_data(
    data_annual,
    filter_options=filter_options(min_stock_price=1),
    rebalancing_month=7,
)