Learn R Programming

PortfolioTesteR (version 0.1.4)

limit_positions: Limit per-date selections to top-K (legacy API)

Description

Legacy selector used across examples/vignettes. Works on a WIDE table (Date + one column per symbol) and returns a WIDE logical mask with at most max_positions TRUE values per row.

Usage

limit_positions(
  selection_df,
  max_positions,
  ranking_signal = NULL,
  verbose = FALSE
)

Value

A data.table with the same columns as selection_df, where symbol columns are logical and at most max_positions are TRUE in each row.

Arguments

selection_df

data.frame/data.table with columns: Date, then one column per symbol; logical (preferred) or numeric (non-NA/ >0 means selected).

max_positions

positive integer, maximum selections to keep per row.

ranking_signal

optional data.frame/data.table, same dims & columns as selection_df, numeric scores used to rank within the selected set.

verbose

logical; if TRUE, prints minor diagnostics. Default FALSE.

Details

If ranking_signal is supplied, it must have the same shape and columns as selection_df; the function keeps the top-K (largest) scores among the currently selected columns in that row. If ranking_signal is NULL, it falls back to the values in selection_df (if numeric), otherwise keeps the first K selected symbols in column order (deterministic).

Examples

Run this code
# \donttest{
  data(sample_prices_weekly)
  mom12 <- PortfolioTesteR::calc_momentum(sample_prices_weekly, 12)  # WIDE numeric
  sel10 <- PortfolioTesteR::filter_top_n(mom12, 10)                  # WIDE logical/numeric
  # Ensure logical mask
  syms <- setdiff(names(sel10), "Date")
  sel_mask <- data.table::as.data.table(sel10)
  sel_mask[, (syms) := lapply(.SD, function(z) as.logical(as.integer(z))), .SDcols = syms]

  # Keep at most 10 per date using momentum as the ranking signal
  lim <- limit_positions(selection_df = sel_mask, max_positions = 10L,
                         ranking_signal = mom12, verbose = FALSE)
  head(lim)
# }

Run the code above in your browser using DataLab