The world is enmeshed in a trade war. The president has been impeached. The tech industry is under attack from regulators worldwide.

But this year investors said: So what?

The stock market is closing in on its best year in two decades. With only two days of trading to go, the S&P 500 could fare better than it has since 1997. Stock prices have been buoyed by a mere whiff of optimism that the economy — despite occasional hiccups and dire prognostications by so-called experts — will keep chugging along.

And the Federal Reserve deserves credit, too, for cutting interest rates despite scowls from a White House that wanted more.

So far this year, the S&P is up 29 percent. But the market crept up gradually as investors felt their way through the turbulent year, interrupted only by a handful of short-lived retreats. Since mid-October, stocks haven’t had a single daily gain of more than 1 percent. Even on Friday, the increase was tiny, but it left the index at a record and capped a fifth consecutive week of gains.

Through the uncertainty, investors saw things they liked: Job growth continued, American consumers kept spending, and President Trump’s bluster about the trade war eventually gave way to promises for an early-stage deal with China.

The damage the trade war might cause was the biggest concern for both investors and the Fed this year. The central bank cut interest rates three times to protect the economy. By December, several key measurements of growth suggested that a recession in the United States was unlikely to ruin the party anytime soon. Major American companies reported that their profits continued to grow, and even the tech industry showed resilience in the face of multiple attacks from presidential candidates and Congress.