The S&P 500 posted its biggest quarterly gain since the end of 2015, as a brightening economic outlook offset investors’ waning enthusiasm for the “Trump trade.”

The index’s 5.5% rise in the first three months of the year extended postelection gains that have sent major U.S. indexes to records, but the most recent move higher reflects a change in the bets that are fueling the rally.

Investors...