It was December 2018, and the towering giants of tech were looking wobbly.

Apple’s shares were tumbling, and it hadn’t yet delivered the bad news about a sales slowdown in China for the iPhone, a device that had helped make it the modern era’s first trillion-dollar company. Facebook could not escape the shadow of the dueling electoral scandals of Cambridge Analytica and Russian disinformation. And Amazon’s stock was sagging as the president of the United States regularly attacked the company.

Just as it appeared that the big tech companies’ endless upward march had finally come to an end, they led a remarkable rally.

This year, the S&P 500 tech sector is up more than 40 percent, handily outpacing the 25 percent gain for the benchmark index over all, which is itself the third-best annual return of the past two decades.

Apple stock is up 70 percent, and it set a high-water mark last week. Google’s parent company, Alphabet, is up 28.5 percent, and set its own record on Monday. Microsoft shares have soared 49 percent in 2019, and Amazon is up 16 percent.