code: def balance_of_contacts(records, weighted=True):
      
      counter_out = defaultdict(int)
      counter = defaultdict(int)
  
      for r in records:
          if r.direction == 'out':
              counter_out[r.correspondent_id] += 1
          counter[r.correspondent_id] += 1
  
      if not weighted:
          balance = [counter_out[c] / counter[c] for c in counter]
      else:
          balance = [counter_out[c] / sum(counter.values()) for c in counter]
  
      return summary_stats(balance)
docs: The balance of interactions per contact. For every contact,
      the balance is the number of outgoing interactions divided by the total
      number of interactions (in+out).
  
      .. math::
  
         \\forall \\,\\text{contact}\\,c,\\;\\text{balance}\,(c) = \\frac{\\bigl|\\text{outgoing}\,(c)\\bigr|}{\\bigl|\\text{outgoing}\,(c)\\bigr|+\\bigl|\\text{incoming}\,(c)\\bigr|}
  
      Parameters
      ----------
      weighted : str, optional
          If ``True``, the balance for each contact is weighted by
          the number of interactions the user had with this contact.