Use indexable clause calculating stock
The query returned compute_quantities_query() uses Coalesce like this:
Coalesce(move.effective_date, move.planned_date, datetime.date.max) > period.date
The problem is that PostgreSQL is not capable of using existing effective_date and planned_date indexes resulting in a Sequential Scan of the whole stock_move table although there are stock periods closed and thus kills performance in a +9M rows table,
The complete query takes +11 seconds.
The problem can alleviated by replacing the above expression with:
(move.effective_date > period.date) | ((move.effective_date == Null) & (move.planned_date > period.date)) | ((move.effective_date == Null) & (move.planned_date == Null))
Bringing the query execution time down to 0.9 seconds.