code: def gen_portfolio(
      model, system, group, tframe, startcap=100000, posby="close"
  ):
      r"""Create a portfolio from a trades frame.
  
      Parameters
      ----------
      model : alphapy.Model
          The model with specifications.
      system : str
          Name of the system.
      group : alphapy.Group
          The group of instruments in the portfolio.
      tframe : pandas.DataFrame
          The input trade list from running the system.
      startcap : float
          Starting capital.
      posby : str
          The position sizing column in the price dataframe.
  
      Returns
      -------
      p : alphapy.Portfolio
          The generated portfolio.
  
      Raises
      ------
      MemoryError
          Could not allocate Portfolio.
  
      Notes
      -----
  
      This function also generates the files required for analysis
      by the *pyfolio* package:
  
      * Returns File
      * Positions File
      * Transactions File
  
      """
  
      logger.info("Creating Portfolio for System %s", system)
  
      # Unpack the model data.
  
      directory = model.specs["directory"]
      extension = model.specs["extension"]
      separator = model.specs["separator"]
  
      # Create the portfolio.
  
      gname = group.name
      gspace = group.space
      gmembers = group.members
      ff = 1.0 / len(gmembers)
  
      p = Portfolio(
          gname,
          system,
          gspace,
          startcap=startcap,
          posby=posby,
          restricted=False,
          fixedfrac=ff,
      )
      if not p:
          raise MemoryError("Could not allocate Portfolio")
  
      # Build pyfolio data from the trades frame.
  
      start = tframe.index[0]
      end = tframe.index[-1]
      trange = np.unique(
          tframe.index.map(lambda x: x.date().strftime("%Y-%m-%d"))
      ).tolist()
      drange = date_range(start, end).map(
          lambda x: x.date().strftime("%Y-%m-%d")
      )
  
      # Initialize return, position, and transaction data.
  
      rs = []
      pcols = list(gmembers)
      pcols.extend(["cash"])
      pf = DataFrame(index=drange, columns=pcols).fillna(0.0)
      ts = []
  
      # Iterate through the date range, updating the portfolio.
      for d in drange:
          # process today's trades
          if d in trange:
              trades = tframe.loc[d]
              if isinstance(trades, Series):
                  trades = DataFrame(trades).transpose()
              for t in trades.iterrows():
                  tdate = t[0]
                  row = t[1]
                  tsize = exec_trade(
                      p,
                      row["name"],
                      row["order"],
                      row["quantity"],
                      row["price"],
                      tdate,
                  )
                  if tsize != 0:
                      ts.append((d, [tsize, row["price"], row["name"]]))
                  else:
                      logger.info(
                          "Trade could not be executed for %s",
                          row["name"],
                      )
          # iterate through current positions
          positions = p.positions
          pfrow = pf.loc[d]
          for key in positions:
              pos = positions[key]
              if pos.quantity > 0:
                  value = pos.value
              else:
                  value = -pos.value
              pfrow[pos.name] = value
          pfrow["cash"] = p.cash
          # update the portfolio returns
          p = valuate_portfolio(p, d)
          rs.append((d, [p.netreturn]))
  
      # Create systems directory path
  
      system_dir = SSEP.join([directory, "systems"])
  
      # Create and record the returns frame for this system.
  
      logger.info("Recording Returns Frame")
      rspace = Space(system, "returns", gspace.fractal)
      rf = DataFrame.from_dict(
          dict(rs), orient="index", columns=["return"]
      )
      rfname = frame_name(gname, rspace)
      write_frame(
          rf,
          system_dir,
          rfname,
          extension,
          separator,
          index=True,
          index_label="date",
      )
      del rspace
  
      # Record the positions frame for this system.
  
      logger.info("Recording Positions Frame")
      pspace = Space(system, "positions", gspace.fractal)
      pfname = frame_name(gname, pspace)
      write_frame(
          pf,
          system_dir,
          pfname,
          extension,
          separator,
          index=True,
          index_label="date",
      )
      del pspace
  
      # Create and record the transactions frame for this system.
  
      logger.info("Recording Transactions Frame")
      tspace = Space(system, "transactions", gspace.fractal)
      tf = DataFrame.from_dict(
          dict(ts),
          orient="index",
          columns=["amount", "price", "symbol"],
      )
      tfname = frame_name(gname, tspace)
      write_frame(
          tf,
          system_dir,
          tfname,
          extension,
          separator,
          index=True,
          index_label="date",
      )
      del tspace
  
      # Return the portfolio.
      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 17 for calling a global function with example usage: gen_portfolio(model, system, group, tframe, startcap, posby) and returns: p