title: Pandas: cumulative sum with conditional subtraction
body: <p>Consider a pandas dataframe like:</p>
  
  <pre class="lang-py prettyprint-override"><code>&gt;&gt; df
  
  date_time            op_type  price  volume
  01-01-1970 9:30:01     ASK     100    1800 
  01-01-1970 9:30:25     ASK      90    1000      
  01-01-1970 9:30:28     BID      90     900
  01-01-1970 9:30:28    TRADE     90     900
  01-01-1970 9:31:01     BID      80     500
  01-01-1970 9:31:09     ASK      80     100
  01-01-1970 9:31:09    TRADE     80     100
  </code></pre>
  
  <p>I would like to do three calculations: <em>i)</em> the cumulative sum of the volume for <code>op_type == "ASK"</code> rows; <em>ii)</em> the cumulative sum of the volume for <code>op_type == "BID"</code> rows; and <em>iii)</em> the sum of the previous two volumes.</p>
  
  <p>That is simple enough, but there is a condition for <code>op_type == "TRADE"</code> operations:</p>
  
  <ol>
  <li><p>Whenever there is a <code>TRADE</code> operation whose <code>price</code> matches the <code>price</code> on a <code>BID</code> operation, I would like to subtract that <code>TRADE</code> operation's volume from the cumulative <code>BID</code> volume.</p></li>
  <li><p>Whenever there is a <code>TRADE</code> operation whose <code>price</code> matches the <code>price</code> on an <code>ASK</code> operation, I would like to subtract that <code>TRADE</code> operation's volume from the cumulative <code>ASK</code> volume.</p></li>
  </ol>
  
  <p>The output I'm looking for is:</p>
  
  <pre class="lang-py prettyprint-override"><code>&gt;&gt; df
  
  date_time            op_type  price  volume  ASK_vol  BID_vol  BIDASK_vol
  01-01-1970 9:30:01     ASK     100    1800    1800       0        1800
  01-01-1970 9:30:25     ASK      90    1000    2800       0        2800
  01-01-1970 9:30:28     BID      90     900    2800      900       3700
  01-01-1970 9:30:28    TRADE     90     900    2800       0        2800
  01-01-1970 9:31:01     BID      80     500    2800      500       3300
  01-01-1970 9:31:09     ASK      80     100    2900      500       3400
  01-01-1970 9:31:09    TRADE     80     100    2800      500       3300
  </code></pre>
  
  <p>I read <a href="https://stackoverflow.com/questions/41420822/python-pandas-conditional-cumulative-sum">this question</a> but I'm not sure how to incorporate the conditional subtraction to that answer. I would greatly appreciate any help, thank you.</p>