title: Improve multiple SQL query performance in python
body: <p>I have a Postgre database that I update everyday to hold stock tickers and prices. I use this database to download stock prices for various dates in a script I'm working on. However, I've noticed that the SQL statement queries taking significantly longer to perform when executed in Python vs. the psql command line.</p>
  
  <p>Does anyone have any idea what I can do to improve the performance of the code below? I've tried combining the SQL queries into one long query but it doesn't seem to work. Thank you!</p>
  
  <pre><code>    for ticker in sectorStocks:
  
      # Pull closing price for startDate
      with con:
          cur = con.cursor()
          cur.execute("SELECT close_price FROM dailyprices WHERE ticker=%s AND price_date=%s", (ticker,startDate))
          tickerStartRaw = cur.fetchone()
  
      # Check to ensure there is market data for the date used
      while not tickerStartRaw:
          startDate = startDate - BDay(1)
          with con:
              cur = con.cursor()
              cur.execute("SELECT close_price FROM dailyprices WHERE ticker=%s AND price_date=%s", (ticker,startDate))
              tickerStartRaw = cur.fetchone()
  
      tickerStartPrice = tickerStartRaw[0]
  
      # Pull closing price for endDate
      with con:
          cur = con.cursor()
          cur.execute("SELECT close_price FROM dailyprices WHERE ticker=%s AND price_date=%s", (ticker,endDate))
          tickerEndRaw = cur.fetchone()
  
      # Check to ensure there is market data for the date used
      while not tickerEndRaw:
          endDate = endDate - BDay(1)
          with con:
              cur = con.cursor()
              cur.execute("SELECT close_price FROM dailyprices WHERE ticker=%s AND price_date=%s", (ticker,endDate))
              tickerEndRaw = cur.fetchone()
  
      tickerEndPrice = tickerEndRaw[0]
  </code></pre>