Have a look at product.py in the stock module, specifically the get_product_available method. This allows you to pack various filter parameters into the context and then it calculates and returns stock as the net of inbound and outbound stock moves.
This method also gets used in the functional fields qty_available
, virtual_available
, incoming_qty
and outgoing_qty
. There is reasonably good explanations in the help comments in the module.