U.S. stocks advanced, sending the Standard & Poor’s 500-stock index near the highest level in about three years, amid optimism Greece will get a bailout.

Banks had the biggest gain in the S&P 500 among 24 groups, rallying 1.7 percent. H.J. Heinz, the biggest ketchup maker, climbed 4.6 percent and Campbell Soup gained 2.6 percent as earnings beat projections. Gilead Sciences tumbled 14 percent as some patients relapsed on its hepatitis C drug. General Mills, the maker of Cheerios cereal, retreated 3.6 percent after cutting its profit forecast.

The S&P 500 rose 0.2 percent to 1,361.23. The index is 0.2 percent below its April peak of 1,363.61, the highest level since June 2008. The Dow Jones industrial average added 45.79 points, or 0.4 percent, to 12,949.87.

Equities rose as euro-zone governments closed in on a deal to unlock a $170 billion aid package for Greece, seeking to avert the region’s first sovereign default. Germany signaled that finance ministers may be ready to back Greece’s second bailout in two years when they meet Monday.

“If things don’t go quite smoothly as expected, then the market would experience a fairly steep selloff,” said Eric Thorne of Bryn Mawr (Pa.) Trust Co.

Stocks also climbed as reports on U.S. manufacturing, housing and jobs bolstered optimism. Friday’s gain extended this year’s rally in the S&P 500 to 8.2 percent.

Seven out of 10 groups in the S&P 500 rose Friday as consumer discretionary and financial shares had the biggest gains. The KBW Bank Index of 24 stocks added 1 percent. J.P. Morgan Chase advanced 1.2 percent to $38.47. Bank of America lost 0.9 percent to $8.02. Intel had the biggest advance in the Dow, rallying 2 percent to $27.37, the highest level since 2007.

Gilead tumbled 14 percent to $47. Among eight patients with hepatitis C genotype 1 in a clinical trial, six had a viral relapse within four weeks after stopping a 12-week treatment with the medicine, GS-7977, plus ribavirin, Gilead said Friday.

The companies investors hated the most in 2011 have returned twice as much as the S&P 500 this year, burning speculators who bet stocks from Sears Holdings to Netflix would keep falling.

The 26 companies in the S&P 500 with the highest short interest relative to shares available for trading rallied 18 percent this year, compared with 8 percent for the full index, data compiled by Bloomberg show. Speculators who borrowed Sears shares and sold them to profit from a drop got hammered as the stock surged 73 percent. Netflix, with short interest of 17 percent at the end of 2011, rose 76 percent.