S&P 500 gains near the end of frenetic week