Investors closed out a rocky month that saw the S&P 500 flirt with bear-market territory amid inflation and recession fears.