code: def kick_out(p, tdate):
      r"""Trim the portfolio based on filter criteria.
  
      To reduce a portfolio's positions, AlphaPy can rank the
      positions on some criterion, such as open profit or net
      return. On a periodic basis, the worst performers can be
      culled from the portfolio.
  
      Parameters
      ----------
      p : alphapy.Portfolio
          The portfolio for reducing positions.
      tdate : datetime
          The date to trim the portfolio positions.
  
      Returns
      -------
      p : alphapy.Portfolio
          The reduced portfolio.
  
      Notes
      -----
  
      .. warning:: The portfolio management functions ``kick_out``,
         ``balance``, and ``stop_loss`` are not part of the
         main **StockStream** pipeline, and thus have not been
         thoroughly tested. Feel free to exercise the code and
         report any issues.
  
      """
      positions = p.positions
      maxpos = p.maxpos
      numpos = len(positions)
      kovalue = np.zeros(numpos)
      koby = p.koby
      if not koby:
          koby = "profit"
      if koby[0] == "-":
          descending = True
          koby = koby[1:]
      else:
          descending = False
      attrs = [
          aname
          for aname in dir(positions[0])
          if not aname.startswith("_")
      ]
      for i, pos in enumerate(positions):
          if koby in attrs:
              estr = ".".join("pos", koby)
              kovalue[i] = eval(estr)
          else:
              kovalue[i] = pos.pdata.loc[tdate][koby]
      koorder = np.argsort(np.argsort(kovalues))
      if descending:
          koorder = [i for i in reversed(koorder)]
      if numpos >= maxpos:
          freepos = numpos - maxpos + p.kopos
          # close the top freepos positions
          if freepos > 0:
              for i in range(freepos):
                  p = close_position(p, positions[koorder[i]], tdate)
      return p
  
imports: from alphapy.frame import Frame
  from alphapy.frame import frame_name
  from alphapy.frame import read_frame
  from alphapy.frame import write_frame
  from alphapy.globals import MULTIPLIERS, SSEP
  from alphapy.globals import Orders
  from alphapy.space import Space
  import logging
  import math
  import numpy
  from pandas import DataFrame
  from pandas import date_range
  from pandas import Series
label_desc: Use image node_id 12 for calling a global function with example usage: kick_out(p, tdate) and returns: p