portfolios.compute_portfolio_returns()
Compute portfolio returns.
Usage
portfolios.compute_portfolio_returns(
data,
sorting_variables,
sorting_method,
rebalancing_month=None,
holding_period=1,
skip=0,
breakpoint_options_main=None,
breakpoint_options_secondary=None,
breakpoint_function_main=compute_breakpoints,
breakpoint_function_secondary=compute_breakpoints,
min_portfolio_size=1,
cap_weight=0.8,
cap_weight_exchanges="NYSE",
data_options=None,
quiet=False
)Computes individual portfolio returns based on specified sorting variables and sorting methods. The portfolios can be rebalanced every period or on an annual frequency by specifying a rebalancing month, which is only applicable at a monthly return frequency. The function supports univariate and bivariate sorts, with the latter supporting dependent and independent sorting methods.
Holding periods and skips are counted on the grid of dates in ‘data’, which must therefore not have gaps (e.g., one row per stock-month in a monthly panel). With staggered rebalancing (‘holding_period > 1’ or ‘skip > 0’), the returned panel starts on the first date on which all ‘holding_period’ cohorts are held.
The function checks for consistency in the provided arguments. For univariate sorts, a single sorting variable and a corresponding number of portfolios must be provided. For bivariate sorts, two sorting variables and two corresponding numbers of portfolios (or percentiles) are required. The sorting method determines how portfolios are assigned and how returns are computed. The function handles missing and extreme values appropriately based on the specified sorting method and rebalancing frequency.
Parameters
data: pl.DataFrame-
Stock-level panel. Must contain the id, date, and excess return columns (configurable via ‘data_options’), the sorting variable(s), and optionally a market-cap lag column for value-weighted returns.
sorting_variables: str or list of str-
Column name(s) in ‘data’ to use for sorting and portfolio assignment. For univariate sorts, provide a single variable. For bivariate sorts, provide two variables, where the first string refers to the main variable and the second string refers to the secondary (‘control’) variable.
sorting_method: {‘univariate’, ‘bivariate-dependent’,-
‘bivariate-independent’} Sorting method to use. For bivariate sorts, the portfolio returns are averaged over the controlling sorting variable (i.e., the second sorting variable), and only portfolio returns for the main sorting variable are returned.
rebalancing_month: int = None-
Integer between 1 and 12 specifying the month in which to form portfolios that are held constant for one year. For example, setting it to 7 creates portfolios in July that are held constant until June of the following year. The default None corresponds to periodic rebalancing.
holding_period: int = 1-
Number of periods for which portfolios are held. With the default 1, portfolios are rebalanced every period. With ‘holding_period=K > 1’, portfolios are formed every period and each cohort is held for K periods, so that K overlapping cohorts are held at any time (staggered rebalancing, as in Jegadeesh and Titman, 1993). The return of a portfolio in a period is the equal-weighted average of the returns of the cohorts held in that period; within a cohort, returns are weighted as in the ’ret_excess_*’ columns, using the weights of the holding period. A stock stays in its cohort for the whole holding period even if its sorting variables are missing in a later period. Cannot be combined with ‘rebalancing_month’.
skip: int = 0-
Number of periods between portfolio formation and the first holding period. The default 0 holds a cohort from the period in which it is formed, consistent with sorting variables that are already lagged (i.e., known at the start of the period). Jegadeesh and Titman (1993), e.g., also report strategies that skip one period. Cannot be combined with ‘rebalancing_month’.
breakpoint_options_main: dict = None-
Named dict of ‘breakpoint_options’ passed to ‘breakpoint_function_main’ for the main sorting variable. Required.
breakpoint_options_secondary: dict = None-
Named dict of ‘breakpoint_options’ passed to ‘breakpoint_function_secondary’. Required for bivariate sorts.
breakpoint_function_main: callable = compute_breakpoints-
Function to compute breakpoints for the main sorting variable. Defaults to ‘compute_breakpoints’.
breakpoint_function_secondary: callable = compute_breakpoints-
Function to compute breakpoints for the secondary sorting variable. Defaults to ‘compute_breakpoints’.
min_portfolio_size: int = 1-
Minimum number of firms required in the reported portfolio cross-section on a given date. For univariate sorts that is firms per portfolio-date; for bivariate sorts that is firms per main-portfolio-date summed across the secondary buckets. Cross-sections below the threshold have their returns set to null. A typical value is 5 (the Fama-French convention). Set to 0 to deactivate the check entirely.
cap_weight: float = 0.8-
Quantile of the cross-sectional ‘mktcap_lag’ distribution at which market capitalizations are capped per date when computing the capped value-weighted excess return (‘ret_excess_vw_capped’). Must be in [0, 1].
cap_weight_exchanges: str or list of str = "NYSE"-
Exchange(s) whose stocks determine the cap: market capitalization is capped at the ‘cap_weight’ percentile of the stocks listed on these exchanges on each date. Defaults to ‘NYSE’, following Jensen, Kelly, and Pedersen (2023), who cap at the 80th percentile of NYSE stocks. None uses all stocks. If the exchange column (mapped via ‘data_options’) is missing, or no stock is listed on these exchanges on a date, the percentile of all stocks is used and a warning says so.
data_options: dict = None-
Column-name mapping (see ‘data_options’). The ‘id’, ‘date’, ‘ret_excess’, and ‘mktcap_lag’ elements are used, and ‘exchange’ with ‘cap_weight_exchanges’. Uses ‘data_options’ defaults when None.
quiet: bool = False- If True, suppress informational warnings about missing observations in the output panel and about the fallback of ‘cap_weight_exchanges’.
Returns
pl.DataFrame-
Data frame with computed portfolio returns as a complete panel (all portfolio-date combinations), containing:
- ‘portfolio’: Portfolio identifier.
- date column (as in ‘data_options’): Date of the portfolio return.
- ‘ret_excess_vw’: Value-weighted excess return (only if ‘data’ contains the market-cap lag column). Null if insufficient observations.
- ‘ret_excess_ew’: Equal-weighted excess return. Null if insufficient observations.
- ‘ret_excess_vw_capped’: Capped value-weighted excess return (only if ‘data’ contains the market-cap lag column). Weights are computed using market capitalization capped at the ‘cap_weight’ percentile per date (see ‘cap_weight_exchanges’). Null if insufficient observations.
Notes
Ensure that ‘data’ contains all required columns: the specified sorting variables and excess returns (see options and defaults set in ‘data_options’). A ValueError is raised if any required column is missing.
In dependent bivariate sorts, the minimum market cap of ‘breakpoints_min_size_threshold’ in ‘breakpoint_options_main’ is computed once per date from the full cross-section, not within each secondary portfolio. This applies to the default ‘compute_breakpoints’; custom breakpoint functions receive their options unchanged.
References
Jegadeesh, N., & Titman, S. (1993). Returns to buying winners and selling losers: Implications for stock market efficiency. Journal of Finance, 48(1), 65-91. https://doi.org/10.1111/j.1540-6261.1993.tb04702.x
Jensen, T. I., Kelly, B., & Pedersen, L. H. (2023). Is there a replication crisis in finance? Journal of Finance, 78(5), 2465-2518. https://doi.org/10.1111/jofi.13249
Examples
import datetime as dt
import numpy as np
import polars as pl
from tidyfinance import (
compute_portfolio_returns,
breakpoint_options,
)
rng = np.random.default_rng(42)
dates = pl.date_range(
dt.date(2020, 1, 1), dt.date(2028, 4, 1), '1mo', eager=True
)
data = pl.DataFrame({
'permno': range(1, 501),
'date': dates.to_numpy().repeat(5),
'mktcap_lag': rng.uniform(100, 1000, 500),
'ret_excess': rng.standard_normal(500),
'size': rng.uniform(50, 150, 500),
})
# Univariate sorting with periodic rebalancing
compute_portfolio_returns(
data, 'size', 'univariate',
breakpoint_options_main=breakpoint_options(n_portfolios=5),
)
# Bivariate dependent sorting with annual rebalancing
compute_portfolio_returns(
data, ['size', 'mktcap_lag'], 'bivariate-dependent', 7,
breakpoint_options_main=breakpoint_options(n_portfolios=5),
breakpoint_options_secondary=breakpoint_options(n_portfolios=3),
)