Dow, S&P 500 retreat from records, close with gains