nodes: 0, module; 1, function_definition; 2, function_name:calc_trades; 3, parameters; 4, block; 5, identifier:current_contracts; 6, identifier:desired_holdings; 7, identifier:trade_weights; 8, identifier:prices; 9, identifier:multipliers; 10, dictionary_splat_pattern; 11, expression_statement; 12, if_statement; 13, expression_statement; 14, for_statement; 15, if_statement; 16, expression_statement; 17, for_statement; 18, expression_statement; 19, expression_statement; 20, expression_statement; 21, expression_statement; 22, return_statement; 23, identifier:kwargs; 24, comment:"""
      Calculate the number of tradeable contracts for rebalancing from a set
      of current contract holdings to a set of desired generic notional holdings
      based on prevailing prices and mapping from generics to tradeable
      instruments. Differences between current holdings and desired holdings
      are treated as 0. Zero trades are dropped.
  
      Parameters
      ----------
      current_contracts: pandas.Series
          Series of current number of contracts held for tradeable instruments.
          Can pass 0 if all holdings are 0.
      desired_holdings: pandas.Series
          Series of desired holdings in base notional currency of generics. Index
          is generic contracts, these should be the same generics as in
          trade_weights.
      trade_weights: pandas.DataFrame or dict
          A pandas.DataFrame of loadings of generic contracts on tradeable
          instruments **for a given date**. The columns refer to generic
          contracts and the index is strings representing instrument names.
          If dict is given keys should be root generic names, e.g. 'CL', and
          values should be pandas.DataFrames of loadings. The union of all
          columns should be a superset of the desired_holdings.index
      prices: pandas.Series
          Series of instrument prices. Index is instrument name and values are
          number of contracts. Extra instrument prices will be ignored.
      multipliers: pandas.Series
          Series of instrument multipliers. Index is instrument name and
          values are the multiplier associated with the contract.
          multipliers.index should be a superset of mapped desired_holdings
          intruments.
      kwargs: key word arguments
          Key word arguments to be passed to to_contracts()
  
      Returns
      -------
      A pandas.Series of instrument contract trades, lexigraphically sorted.
  
      Example
      -------
      >>> import pandas as pd
      >>> import mapping.util as util
      >>> wts = pd.DataFrame([[0.5, 0], [0.5, 0.5], [0, 0.5]],
      ...                    index=["CLX16", "CLZ16", "CLF17"],
      ...                    columns=["CL1", "CL2"])
      >>> desired_holdings = pd.Series([200000, -50000], index=["CL1", "CL2"])
      >>> current_contracts = pd.Series([0, 1, 0],
      ...                               index=['CLX16', 'CLZ16', 'CLF17'])
      >>> prices = pd.Series([50.32, 50.41, 50.48],
      ...                    index=['CLX16', 'CLZ16', 'CLF17'])
      >>> multipliers = pd.Series([100, 100, 100],
      ...                        index=['CLX16', 'CLZ16', 'CLF17'])
      >>> trades = util.calc_trades(current_contracts, desired_holdings, wts,
      ...                           prices, multipliers)
      """; 25, not_operator; 26, block; 27, assignment; 28, identifier:key; 29, identifier:trade_weights; 30, block; 31, not_operator; 32, block; 33, assignment; 34, identifier:root_key; 35, identifier:trade_weights; 36, block; 37, assignment; 38, assignment; 39, assignment; 40, assignment; 41, identifier:trades; 42, call; 43, expression_statement; 44, identifier:generics; 45, list; 46, expression_statement; 47, call; 48, raise_statement; 49, identifier:desired_contracts; 50, list; 51, expression_statement; 52, expression_statement; 53, expression_statement; 54, expression_statement; 55, comment:# drop indexes where all non zero weights were in columns dropped above; 56, expression_statement; 57, expression_statement; 58, expression_statement; 59, expression_statement; 60, expression_statement; 61, identifier:desired_contracts; 62, call; 63, identifier:trades; 64, call; 65, identifier:trades; 66, subscript; 67, identifier:trades; 68, call; 69, identifier:isinstance; 70, argument_list; 71, assignment; 72, call; 73, attribute; 74, argument_list; 75, call; 76, assignment; 77, assignment; 78, assignment; 79, assignment; 80, assignment; 81, assignment; 82, assignment; 83, assignment; 84, call; 85, attribute; 86, argument_list; 87, attribute; 88, argument_list; 89, attribute; 90, comparison_operator:trades != 0; 91, attribute; 92, argument_list; 93, identifier:trade_weights; 94, identifier:dict; 95, identifier:trade_weights; 96, dictionary; 97, attribute; 98, argument_list; 99, call; 100, identifier:issubset; 101, call; 102, identifier:ValueError; 103, argument_list; 104, identifier:gnrc_weights; 105, subscript; 106, identifier:subset; 107, call; 108, identifier:gnrc_des_hlds; 109, subscript; 110, identifier:gnrc_weights; 111, subscript; 112, identifier:gnrc_weights; 113, subscript; 114, identifier:instr_des_hlds; 115, binary_operator:gnrc_des_hlds * gnrc_weights; 116, identifier:instr_des_hlds; 117, call; 118, identifier:wprices; 119, subscript; 120, attribute; 121, argument_list; 122, identifier:pd; 123, identifier:concat; 124, identifier:desired_contracts; 125, keyword_argument; 126, identifier:desired_contracts; 127, identifier:subtract; 128, identifier:current_contracts; 129, keyword_argument; 130, identifier:trades; 131, identifier:loc; 132, identifier:trades; 133, integer:0; 134, identifier:trades; 135, identifier:sort_index; 136, pair; 137, identifier:generics; 138, identifier:extend; 139, attribute; 140, identifier:set; 141, argument_list; 142, identifier:set; 143, argument_list; 144, call; 145, identifier:trade_weights; 146, identifier:root_key; 147, attribute; 148, argument_list; 149, attribute; 150, identifier:subset; 151, attribute; 152, slice; 153, identifier:subset; 154, attribute; 155, unary_operator; 156, identifier:gnrc_des_hlds; 157, identifier:gnrc_weights; 158, attribute; 159, argument_list; 160, attribute; 161, attribute; 162, identifier:desired_contracts; 163, identifier:append; 164, call; 165, identifier:axis; 166, integer:0; 167, identifier:fill_value; 168, integer:0; 169, string:""; 170, identifier:trade_weights; 171, subscript; 172, identifier:columns; 173, attribute; 174, identifier:generics; 175, attribute; 176, argument_list; 177, attribute; 178, identifier:intersection; 179, attribute; 180, identifier:desired_holdings; 181, identifier:loc; 182, identifier:gnrc_weights; 183, identifier:loc; 184, identifier:gnrc_weights; 185, identifier:loc; 186, call; 187, identifier:instr_des_hlds; 188, identifier:sum; 189, keyword_argument; 190, identifier:prices; 191, identifier:loc; 192, identifier:instr_des_hlds; 193, identifier:index; 194, identifier:to_contracts; 195, argument_list; 196, identifier:trade_weights; 197, identifier:key; 198, identifier:desired_holdings; 199, identifier:index; 200, concatenated_string; 201, identifier:format; 202, call; 203, call; 204, identifier:gnrc_weights; 205, identifier:columns; 206, identifier:desired_holdings; 207, identifier:index; 208, attribute; 209, argument_list; 210, identifier:axis; 211, integer:1; 212, identifier:instr_des_hlds; 213, identifier:wprices; 214, identifier:multipliers; 215, dictionary_splat; 216, string:"'desired_holdings.index' contains values which "; 217, string:"cannot be mapped to tradeables.\n"; 218, string:"Received: 'desired_holdings.index'\n {0}\n"; 219, string:"Expected in 'trade_weights' set of columns:\n {1}\n"; 220, identifier:sorted; 221, argument_list; 222, identifier:sorted; 223, argument_list; 224, parenthesized_expression; 225, identifier:all; 226, keyword_argument; 227, identifier:kwargs; 228, attribute; 229, identifier:generics; 230, comparison_operator:gnrc_weights == 0; 231, identifier:axis; 232, integer:1; 233, identifier:desired_holdings; 234, identifier:index; 235, identifier:gnrc_weights; 236, integer:0
code: def calc_trades(current_contracts, desired_holdings, trade_weights, prices,
                  multipliers, **kwargs):
      """
      Calculate the number of tradeable contracts for rebalancing from a set
      of current contract holdings to a set of desired generic notional holdings
      based on prevailing prices and mapping from generics to tradeable
      instruments. Differences between current holdings and desired holdings
      are treated as 0. Zero trades are dropped.
  
      Parameters
      ----------
      current_contracts: pandas.Series
          Series of current number of contracts held for tradeable instruments.
          Can pass 0 if all holdings are 0.
      desired_holdings: pandas.Series
          Series of desired holdings in base notional currency of generics. Index
          is generic contracts, these should be the same generics as in
          trade_weights.
      trade_weights: pandas.DataFrame or dict
          A pandas.DataFrame of loadings of generic contracts on tradeable
          instruments **for a given date**. The columns refer to generic
          contracts and the index is strings representing instrument names.
          If dict is given keys should be root generic names, e.g. 'CL', and
          values should be pandas.DataFrames of loadings. The union of all
          columns should be a superset of the desired_holdings.index
      prices: pandas.Series
          Series of instrument prices. Index is instrument name and values are
          number of contracts. Extra instrument prices will be ignored.
      multipliers: pandas.Series
          Series of instrument multipliers. Index is instrument name and
          values are the multiplier associated with the contract.
          multipliers.index should be a superset of mapped desired_holdings
          intruments.
      kwargs: key word arguments
          Key word arguments to be passed to to_contracts()
  
      Returns
      -------
      A pandas.Series of instrument contract trades, lexigraphically sorted.
  
      Example
      -------
      >>> import pandas as pd
      >>> import mapping.util as util
      >>> wts = pd.DataFrame([[0.5, 0], [0.5, 0.5], [0, 0.5]],
      ...                    index=["CLX16", "CLZ16", "CLF17"],
      ...                    columns=["CL1", "CL2"])
      >>> desired_holdings = pd.Series([200000, -50000], index=["CL1", "CL2"])
      >>> current_contracts = pd.Series([0, 1, 0],
      ...                               index=['CLX16', 'CLZ16', 'CLF17'])
      >>> prices = pd.Series([50.32, 50.41, 50.48],
      ...                    index=['CLX16', 'CLZ16', 'CLF17'])
      >>> multipliers = pd.Series([100, 100, 100],
      ...                        index=['CLX16', 'CLZ16', 'CLF17'])
      >>> trades = util.calc_trades(current_contracts, desired_holdings, wts,
      ...                           prices, multipliers)
      """
      if not isinstance(trade_weights, dict):
          trade_weights = {"": trade_weights}
  
      generics = []
      for key in trade_weights:
          generics.extend(trade_weights[key].columns)
  
      if not set(desired_holdings.index).issubset(set(generics)):
          raise ValueError("'desired_holdings.index' contains values which "
                           "cannot be mapped to tradeables.\n"
                           "Received: 'desired_holdings.index'\n {0}\n"
                           "Expected in 'trade_weights' set of columns:\n {1}\n"
                           .format(sorted(desired_holdings.index),
                                   sorted(generics)))
  
      desired_contracts = []
      for root_key in trade_weights:
          gnrc_weights = trade_weights[root_key]
  
          subset = gnrc_weights.columns.intersection(desired_holdings.index)
          gnrc_des_hlds = desired_holdings.loc[subset]
          gnrc_weights = gnrc_weights.loc[:, subset]
          # drop indexes where all non zero weights were in columns dropped above
          gnrc_weights = gnrc_weights.loc[~(gnrc_weights == 0).all(axis=1)]
  
          instr_des_hlds = gnrc_des_hlds * gnrc_weights
          instr_des_hlds = instr_des_hlds.sum(axis=1)
          wprices = prices.loc[instr_des_hlds.index]
          desired_contracts.append(to_contracts(instr_des_hlds, wprices,
                                                multipliers, **kwargs))
  
      desired_contracts = pd.concat(desired_contracts, axis=0)
  
      trades = desired_contracts.subtract(current_contracts, fill_value=0)
      trades = trades.loc[trades != 0]
      trades = trades.sort_index()
      return trades