After spending the morning in the red, stocks clawed their way back to gains in afternoon trading while oil prices shifted from a rally to a decline.