Apply grouping logic to portfolio query