Stocks rallied on Thursday as investors were relieved that Federal Reserve Chairman Ben Bernanke withstood congressional questioning without problems.

Retailers and home builders led stocks higher for much of the session, helped by a surprising profit increase from retailer Bed Bath & Beyond Inc

Stocks extended gains shortly before midday as investors took Bernanke's hearing in stride.

The U.S. House of Representatives Oversight and Government Reform Committee questioned Bernanke on the Fed's role in Bank of America's takeover of Merrill Lynch, and whether he pressured BofA's CEO Ken Lewis to go through with the deal after Lewis raised objections.

There was concern as to what might happen there. He seemed to give some pretty decent testimony; at least it didn't get out of hand, said Bucky Hellwig, senior vice president at Morgan Asset Management, in Birmingham, Alabama.

The Dow Jones industrial average <.DJI> was up 172.54 points, or 2.08 percent, at 8,472.40. The Standard & Poor's 500 Index <.SPX> was up 19.32 points, or 2.14 percent, at 920.26. The Nasdaq Composite Index <.IXIC> was up 37.20 points, or 2.08 percent, at 1,829.54.

The Dow snapped a four-day losing streak.

Also boosting the market was home builder Lennar Corp , which posted a wider quarterly loss, but noted an increase in new home sales and orders. Its stock shot up 17.5 percent to $9.19.

The Dow Jones U.S. home construction index <.DJUSHB> jumped 5.9 percent.

Gains in home builders and retailers point to signs of strength in consumer spending, which could be a boon for stocks just as the second-quarter earnings reporting period gets under way.

Another sign that encouraged investors was news the Federal Reserve was scaling back an emergency funding program while extending others.

An auction of $27 billion of 7-year notes attracted strong demand, pressuring U.S. Treasury bond yields. The auction completed this week's record $104 billion sale of Treasury coupons, with all three auctions seeing solid demand.

Higher bond yields mean bigger borrowing costs for consumers.

In the retail sector, Bed Bath & Beyond reported a surprising increase in quarterly profit as it cut costs to offset slumping demand, and its stock gained 9.5 percent to $31.08. The S&P retail index <.RLX> climbed 3.8 percent.

(Additional reporting by Leah Schnurr; Editing by Jan Paschal)