portfolios.assign_portfolio()

Assign data points to portfolios based on a sorting variable.

Usage

Source

portfolios.assign_portfolio(
    data,
    sorting_variable,
    breakpoint_options=None,
    breakpoint_function=None,
    data_options=None
)

Users may pass a custom function to compute breakpoints. The function must take ‘data’ and ‘sorting_variable’ as the first two arguments, then ‘breakpoint_options’ and ‘data_options’. The function must return an ascending sequence of breakpoints. Defaults to compute_breakpoints.

Parameters

data: pl.DataFrame

Dataset for portfolio assignment.

sorting_variable: str

Column in ‘data’ used for sorting and portfolio assignment.

breakpoint_options: dict = None

Named arguments passed to ‘breakpoint_function’. Typically produced by breakpoint_options.

breakpoint_function: callable = None

Function to compute breakpoints. Must return an ascending sequence. Defaults to compute_breakpoints.

data_options: dict = None
Column-name mapping (see data_options). Passed through to ‘breakpoint_function’.

Returns

pl.Series
Portfolio assignments as a Float64 series aligned with the input rows. Each entry is the 1-indexed portfolio number; values outside the breakpoint range fall into the boundary portfolios. Missing inputs are returned as null.

Examples

import numpy as np
import polars as pl
from tidyfinance import assign_portfolio, breakpoint_options
rng = np.random.default_rng(42)
data = pl.DataFrame({
    'exchange': rng.choice(['NYSE', 'NASDAQ'], 100),
    'market_cap': rng.uniform(1, 100, 100),
})
# Quintile portfolios on market_cap with NYSE breakpoints
assign_portfolio(
    data,
    sorting_variable='market_cap',
    breakpoint_options=breakpoint_options(
        n_portfolios=5,
        breakpoints_exchanges='NYSE',
    ),
)