By Gunjan Banerji

U.S. stocks turned in a second consecutive quarter of dramatic gains, continuing a historic stock-market recovery that few predicted in the depths of the March downturn.

The S&P 500 and Nasdaq Composite hit a string of records in the third quarter, a journey that has confounded many investors with its sheer velocity and strength. Despite a stretch of volatility that dampened momentum in September, the S&P 500 and Dow Jones Industrial Average gained 8.5% and 7.6%, respectively, over the past three months.

The advances built on even bigger gains in the previous period, capping the best two-quarter performance since 2009. Both indexes are up more than 26% since the end of March. The Nasdaq Composite surged 11% in the third quarter and rose 45% over the past six months, its biggest two-quarter gain since 2000.

All three indexes climbed Wednesday to end the period on a strong note.

Companies that are new to the public markets have also been embraced by investors. Shares of software companies Palantir Technologies and Asana started trading Wednesday on the New York Stock Exchange, both climbing in their debuts.

Their entrance to the public markets underscores how robust the market for initial public offerings has been this year, particularly as investors have favored technology companies.

Many investors attribute the broader stock market's strong performance to an economy that has steadily improved -- though it remains far from where it was to start the year -- as well as a powerful surge in big technology stocks that has steered the market higher and higher. Consumer spending has ticked up from abysmal levels earlier in the year and hiring in the U.S. has picked up for four consecutive months.

Meanwhile, the Federal Reserve approved a shift in how it sets interest rates in the third quarter, signaling it would leave them low for years.

"The big surprise was the adaptability," said Stephen Lee, a founding principal at Logan Capital Management. "The economy showed how adaptable it is."

Still, there are plenty of potential challenges ahead for investors.

Many are closely tracking the presidential election in November, wary that the result may not be known immediately. This has spurred bets on volatility through the end of the year in markets from derivatives to currencies and bonds.

"In the short-term, both interest rates and risk sentiment have the potential to shift postelection, leading to sharp changes in equity prices," Goldman Sachs analysts wrote Tuesday in a note to clients. The firm expects the S&P 500 to hit 3600 by the end of the year, about a 7% jump from Wednesday's close.

Despite the market's gains since March, stocks are essentially back to where they started the year. The S&P 500 is up 4.1% for 2020, while the Dow industrials are down 2.7%. Only the tech-heavy Nasdaq Composite has clinched a meaningful gain for the year, up 24%.

Among the big winners in the third quarter have been shares of home builders, which have benefited from an epic housing boom as the pandemic has created a historic shortage of homes for sale. Americans have been rushing to land more living space, anticipating they will continue working from home during the pandemic.

Shares of D.R. Horton and PulteGroup both jumped 36% in the quarter. Lennar's stock rallied 33%. New Home advanced 62%.

But shares of tech darlings and growth stocks stole the show again, and there have been exceptional moves by the U.S. stock market's behemoths. Apple's valuation crossed the $2 trillion mark, making the iPhone-maker bigger than entire global markets. The company's shares soared 27% over the past three months.

And Tesla surged to a fresh high in August, gaining a market value of more than $400 billion. The shares have almost doubled in the third quarter.

Both stocks have been favorites among institutions, as well as individual investors, many of whom are new to trading stocks or have ramped up activity significantly this year. Some investors grew so optimistic about stocks like these that they turned to the derivatives markets to make aggressive bets on the market, fueling even greater gains at times.

Roadblocks emerged in the tail end of the quarter, pulling major indexes lower and crimping an epic run for the technology sector. The Nasdaq Composite fell into a correction territory -- defined as at least a 10% drop from the recent high -- just three sessions after hitting a record, the speediest-ever such fall. Although the index has since recovered some of the losses, the abrupt fall highlighted how fragile markets appear, and the uncertainty ahead.

"At the first sign of trouble, everyone bailed," said Ilya Feygin, managing director at brokerage WallachBeth Capital.

Stock funds recently saw the biggest weekly outflows since 2018, according to Deutsche Bank. Meanwhile, traditionally safer investments like Treasurys and gold have done well, with gold prices jumping to an all-time high in July.

The yield on the 10-year U.S. Treasury note slipped in September to 0.677% as bond prices rose for the month, though yields ticked higher for the latest quarter.

Concerns remain that coronavirus infections could tick up in the colder months. For example, the daily share of people tested in New York City who are positive for Covid-19 recently hit 3.25% for the first time since June. Additionally, lawmakers so far haven't been able to agree on another stimulus bill for Americans.

The stock rally this quarter ignited greater debate about whether value stocks, those like cyclical companies with relatively low price-to-earnings ratios, would manage to soar past their faster-growing peers.

There has been a recent shift in market leadership between stocks that benefit from Americans' staying at home during the pandemic and those that would get a lift from a prolonged economic recovery, highlighting that much remains unknown about the path of the virus and economy.

"All of this jockeying is because people are uncertain," said Mr. Feygin. "We have a huge amount of uncertainty as to what the path of the virus will be."

But stocks have staged an aggressive rebound in the last few days of the quarter, and some investors say that though there will likely be volatility ahead, the worst may have passed.

"You'll get a wobble if people start to worry that the economy's starting to shut down again," said Eddie Perkin, chief equity investment officer at Eaton Vance. Still, he said "I don't think you'll get a repeat of that deep of a pullback" as in March.

Write to Gunjan Banerji at Gunjan.Banerji@wsj.com