By Michael Wursthorn

U.S. stocks wrapped up their best quarter in more than 20 years, a remarkable rally after the coronavirus pandemic brought business around the world to a virtual standstill.

Just three months ago, investors were lamenting the end of the bull market -- and the longest economic expansion on record -- after major U.S. stock indexes lost about 35% of their value in less than six weeks. The subsequent rebound has been nearly as brisk.

Partly thanks to an unprecedented $1.6 trillion stimulus package from the Federal Reserve and Congress and a surge in trading among individual investors, the rally has lifted everything from beaten-down energy stocks to apparel retailers to big technology firms.

"Massive stimulus by the Fed and on the fiscal side has propelled the stock market's recovery at a speed unlike we've ever seen," said Liz Ann Sonders, a chief investment strategist at Charles Schwab & Co. "But there's a perceived disconnect between what the market has done and the economic recovery. The reality is, the second half of the year may see a lot of choppiness."

The S&P 500 finished the quarter up 20% at 3100, its biggest percentage gain since the fourth quarter of 1998. The Dow Jones Industrial Average rose 18% to 25812, its best quarter since 1987.

The rally has cut the indexes' losses for the year to 4% and 10%, respectively. The Nasdaq Composite, which is heavily weighted toward big tech stocks including Apple Inc. and Microsoft Corp., has fared even better, up 31% in the past three months and 12% for this year.

The path ahead for the stock market is less clear, especially with the November presidential election now coming into view.

A Democratic sweep of the White House and Congress looms as a potential risk to the market in the months ahead. Analysts say a Democratic-controlled government would likely roll back the tax cuts Congress enacted in 2017, constraining corporate profit margins.

The other risk, analysts add, would be the potential for more regulation, which sometimes stifles business activity. Analysts credit some of the stock market's gains in recent years to the Trump administration's reversal of regulatory actions.

The market's rally has slowed lately as a resurgence in coronavirus cases in some parts of the U.S. and protests sparked by the killing of George Floyd, a Black man in police custody, have dented sentiment. After logging in April and May its biggest two-month percentage gain since 2009, the S&P 500 rose just 1.8% in June.

The economic picture also remains bleak. Nearly 20 million jobs have been shed since February, and retail sales are far below prepandemic levels. Manufacturing activity in the U.S. has also contracted, albeit at a more gradual rate.

Predicting how the stock market will fare in the months ahead has never been simple, but the economic crisis wrought by coronavirus has rewritten the traditional investing playbook.

"You have traders trying to figure out a medical problem," said JJ Kinahan, chief market strategist at TD Ameritrade. "Because people will make assumptions or because there's a lack of knowledge, the one thing we can all expect is more volatility."

Michael Scanlon, a portfolio manager at Manulife Investment Management, said he expects stocks to be stuck in a relatively narrow trading range through the end of the year unless there is a breakthrough on a coronavirus treatment. But that hasn't damped his enthusiasm for U.S. stocks relative to equities in other parts of the world.

"This has been the ultimate Peter Lynch market and that will continue," said Mr. Scanlon, referring to the former Fidelity Magellan Fund manager's often-quoted catchphrase, "Invest in what you know." Mr. Scanlon's fund, the $2.6 billion John Hancock Balanced Fund, has bought stocks such as Ulta Beauty Inc. in recent months, betting the cosmetics company will thrive despite the struggles plaguing department stores.

He added the fund has maintained big positions in Microsoft, Amazon.com Inc. and other popular stocks that have rebounded sharply. Mr. Scanlon's fund is up 0.5% so far this year, beating the S&P 500.

Some investors are more bearish, including famed stock picker Jeremy Grantham. Mr. Grantham said on CNBC about two weeks ago that investors buying stocks right now are "simply playing with fire."

A second wave of coronavirus cases was cited as the most prominent risk facing stocks for a fourth consecutive month, according to a survey of 190 fund managers by Bank of America in June. Permanently high unemployment and a Democratic sweep of the election followed.

"Covid is going to outweigh the presidential election at least until October unless there's some sort of shock between now and then," Mr. Kinahan said, referring to the possibility that former Vice President Joe Biden or President Trump releases policy proposals that roil sectors such as health care or financial services.

The stock market's performance in the months ahead of the election could have a big impact on the outcome of the race, though. Data going back to 1928 show the incumbent party has won the contest 87% of the time if the S&P 500 is positive over the three months ahead of the election and lost it when it is negative, said Courtney Rosenberger, director of policy research at Strategas Securities LLC.

The expectation of near-term volatility has led some analysts and money managers to encourage investors to take a shorter-term look at their portfolios, rather than reviewing on a monthly or quarterly basis.

Ms. Sonders said rebalances should be considered as often as every few weeks depending on which sectors and assets run up quickly and which fall. Planning beyond that is difficult because so many companies have suspended their earnings guidance, she added.

More than 180 companies in the S&P 500 have withdrawn their earnings guidance for 2020, according to FactSet, making it increasingly difficult for investors to value stocks. Just 49 companies have issued guidance for the coming second-quarter earnings season, the fewest since FactSet began tracking such data in 2006.

"Valuation is a total crapshoot with a record number of companies withdrawing guidance," Ms. Sonders added. "We can plug in a forward consensus, but there's no clarity around the plugs."

Analysts predict earnings among companies in the S&P 500 will contract 21% this year from 2019, according to FactSet, before beginning to rebound next year. That is a stark reversal from their call at the beginning of the year for 9.2% growth.

The lack of visibility hasn't appeared to slow the market's rebound. Aggressive efforts by the Fed to stabilize credit markets and a massive aid package from Congress that included enhanced unemployment insurance and loans to struggling businesses gave many investors confidence to jump back into the market.

And many analysts say they have been amazed to see individual investors flocking to platforms including Robinhood Markets Inc. that offer zero-commission trades to take advantage of discounted share prices, adding further momentum to the rally.

Big Wall Street banks have revised their targets several times this year to reflect the rapidly changing outlook. The Fed's stimulus made traditional indicators, including unemployment figures and gross domestic product numbers, less reliable for forecasters, JPMorgan analysts wrote in a June research note.

Bank of America's analysts recently put a 2900 year-end price target on the S&P 500, abandoning previous calls of 2600 and 3100 from earlier points in the year. Goldman lifted the low end of its three-month target to 2750 from 2400 in late May as the index hovered around its year-end projection of 3000.

Those targets suggest the stock market has topped out this year and will fall as much as 5% by December.

Others have abandoned their forecasts altogether in light of the uncertainty. BMO Capital Markets suspended its year-end price target on the S&P 500 in March, instead favoring a rolling 12-month target of 3400 -- suggesting stocks will eventually break out of a narrow trading range to climb 11% from the current level.

Write to Michael Wursthorn at Michael.Wursthorn@wsj.com