Nasdaq ends higher while S&P 500 posts biggest August gain since 1986