Just a small update / correction of Quovadisqc's answer. When defining $ qty, it should be
$qty = $stockItem->getData('qty');
Instead of what currently exists,
$qty = $stockItem->setData('qty');
I would post this as a comment, but I don't have enough reputation.
source share