libb.weighted_average

weighted_average(rows, field, predicate, weight_field)[source]

Compute a weighted average of field in a DataSet using weight_field as the weight. Limit to rows matching the predicate. Uses sum of abs in denominator because we are really looking for the value-weighted contribution of the position.

This handles long/short cases correctly, although they can give surprising results.

Consider two “trades” BL 5000 at a delta of 50% and SS -4000 at a delta of 30%. If you didn’t use abs() you’d get:

(5000 * 50 - 4000 * 30) / (5000 - 4000) = 130

Using abs() you get:

(5000 * 50 - 4000 * 30) / (5000 + 4000) = 14.4

This is really equivalent to saying you bought another 4000 at a delta of -30 (because the short position has a negative delta effect) which then makes more sense: combining two positions, one with positive delta and one with negative should give a value that weights the net effect of them, which the second case does. If the short position were larger or had a larger delta, you could end up with a negative weighted average, which although a bit confusing, is mathematically correct.