title: How to merge two lists of dates into a series of date intervals?
body: <p>I have list of start dates, and a list of end dates. They're sorted...</p>
  
  <pre><code>start_dates = [
      datetime.date(2009, 11, 5), datetime.date(2009, 11, 13), 
      datetime.date(2009, 11, 25), datetime.date(2009, 11, 26), 
      datetime.date(2009, 12, 4), datetime.date(2009, 12, 7), 
      datetime.date(2009, 12, 29), datetime.date(2009, 12, 30)]
  
  end_dates = [
      datetime.date(2009, 10, 1), datetime.date(2009, 10, 2), 
      datetime.date(2009, 10, 9), datetime.date(2009, 10, 12), 
      datetime.date(2009, 11, 4), datetime.date(2009, 12, 14), 
      datetime.date(2009, 12, 15)]
  </code></pre>
  
  <p>The start dates represent dates on which we received advice to buy a share. The end dates are dates on which which we received advice to sell it. The sources of advice are different and we are backtesting what would happen if we used the buy advice from one source, but the sell advice from another.  Thus we have two sequences of dates which we want to resolve into pairs - or intervals - over which we would have held a position in the stock.</p>
  
  <p>Thus we'll take a date from the start_dates to decide when to buy the stock: on Nov 5 we buy a position. Then we cycle through the end_dates looking for the first advice to sell it: Dec 14.   And repeat, buying when we don't hold a position when advised to from one source, and selling when we do hold a position from the other source.</p>
  
  <p>You might say we want to flap between which of two lists we're looping over.</p>
  
  <p>Thus the input above generates:</p>
  
  <pre><code>result = (
    (datetime.date(2009, 11, 5), datetime.date(2009, 12, 14)),
    (datetime.date(2009, 12, 29), None)
  )
  </code></pre>
  
  <p>I'm using for-loops inside for-loops and wonder if there is not a better way.  Performance is of interest since it will be applied to thousands of scenarios over a 40 year span; some of the lists involve thousands of dates.</p>