Stocks swerved up and down on Thursday before ending with a modest gain after China sent conflicting signals about how it would respond to President Trump’s threats of new tariffs and investors took some solace in upbeat economic and earnings data.

The positive signs included an increase in retail sales in the United States in July, according to the Commerce Department, and stronger-than-expected earnings from Walmart, which raised its outlook for sales this year. The Chinese e-commerce giant Alibaba also released strong financial results.

By the end of trading Thursday, the S&P 500 gained 0.25 percent. Stocks in Europe ended lower, but clawed back some of their earlier losses.

The swings were just the latest in a turbulent stretch for investors. Markets around the world have been whipsawed this month by mixed signals about the state of the trade war between the United States and China and growing evidence that the dispute is already slowing global growth, especially in the manufacturing sector.