Skip to content

Instantly share code, notes, and snippets.

@coltonbh
Created April 2, 2018 19:07
Show Gist options
  • Save coltonbh/81ca178e237e4400ef958018028ac526 to your computer and use it in GitHub Desktop.
Save coltonbh/81ca178e237e4400ef958018028ac526 to your computer and use it in GitHub Desktop.
For when an absolute value calculation of Max is needed. In this case the 'quantity' value could be negative or positive and I want the largest position from both the long (positive quantity) and short (negative quantity) positions.
from django.db.models import Max, FloatField
class ABSMax(Max):
"""Django annotate/aggregate method for computing the abs max value of
some expression.
"""
name = 'ABSMax'
template = '%(function)s(%(absolute)s(%(expressions)s))'
def __init__(self, expression, **extra):
super().__init__(
expression, absolute='ABS ', output_field=FloatField(), **extra)
def __repr__(self):
return "MAX(ABS(%s))".format(
self.arg_joiner.join(str(arg) for arg in self.source_expressions)
)
USAGE:
def max_exposure_position(self, portfolio):
"""Return position in portfolio with maximum exposure."""
return portfolio.positions.annotate(
max_val=ABSMax(
ExpressionWrapper(
F('quantity') * F('market_price'),
output_field=FloatField()
)
)
).latest('max_val') # latest will get the biggest value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment