A volatile day on Wall Street ended in upbeat fashion Tuesday as a late-afternoon rally led by technology stocks pushed the market to a modest gain.

The turnaround helped snap an eight-day trading slump for the Nasdaq composite, which is heavily weighted with technology stocks.

Energy stocks slumped as much as 2 percent during the day, then recovered in late trading to eke out a slight gain.

Crude oil prices declined for the seventh day in a row, the longest losing streak since July 2014. Oil has now fallen nearly 18 percent this year.

“We saw a little bit of weakness in oil and the selling just continued,” said J.J. Kinahan, chief strategist at TD Ameritrade.

All told, the Dow Jones industrial average gained 117.65 points, or 0.7 percent, to 16,516.22. The Standard & Poor’s 500 index added 15.01 points, or 0.8 percent, to 1,938.68. The Nasdaq composite climbed 47.93 points, or 1 percent, to 4,685.92.

The three major U.S. stock indexes are all down for the year, with the Dow and S&P 500 index off about 5 percent, while the Nasdaq is down 6.4 percent.

advertisement | advertise on newsday

After a positive turn early Tuesday, the market looked like it was headed for a lower close before it reversed course in the final hour of trading.

“You’re seeing very oversold conditions,” said Phil Blancato, CEO of Ladenburg Thalmann Asset Management. “People here are basically buying the dip.”