U.S. stocks gained on Thursday as declining gold and oil prices eased inflation concerns, while an analyst said more mortgage purchases by Fannie Mae and Freddie Mac will help stabilize the home-loan market causing them to surge for a third day on hopes they will stabilize the housing market.

Fannie Mae and Freddie Mac, the biggest sources of money for U.S. mortgages, led gains in the Standard & Poor's 500 Index after Keefe, Bruyette & Woods upgraded the companies shares.

The S&P 500 gained 20.20 points, or 1.56 percent, to 1,318.62 as of 2:16 p.m. in New York. The Dow Jones Industrial Average advanced 183.75, or 1.52 percent, to 12,283.41. The Nasdaq Composite Index rose 30.58, or 1.38 percent, to 2,240.54.

Fannie Mae gained $3.54 to $34.25 while Freddie Mac added $2.68 to $32.58. Keefe, Bruyette & Woods analyst Frederick Cannon upgraded the shares to outperform from market perform.

Concerns over rising inflation eased as commodity prices dropped. Metal and oil investors cashed in investments, taking profits after a series of record peaks this year. Gold moved towards its biggest weekly drop in 25 years while crude oil fell below $100 a barrel for the first time since March 5.