3 # © Copyright 2021-2022, Scott Gasch
5 """A class to represent a rate of change."""
7 from typing import Optional
11 """A class to represent a rate of change."""
15 multiplier: Optional[float] = None,
17 percentage: Optional[float] = None,
18 percent_change: Optional[float] = None,
21 if multiplier is not None:
22 if isinstance(multiplier, str):
23 multiplier = multiplier.replace('%', '')
26 self.multiplier: float = m
28 self.multiplier = multiplier
30 if percentage is not None:
31 self.multiplier = percentage / 100
33 if percent_change is not None:
34 self.multiplier = 1.0 + percent_change / 100
38 'Exactly one of percentage, percent_change or multiplier is required.'
41 def apply_to(self, other):
42 return self.__mul__(other)
45 return self.__mul__(other)
48 return self.multiplier
50 def __mul__(self, other):
51 return self.multiplier * float(other)
55 def __truediv__(self, other):
56 return self.multiplier / float(other)
58 def __add__(self, other):
59 return self.multiplier + float(other)
63 def __sub__(self, other):
64 return self.multiplier - float(other)
66 def __eq__(self, other):
67 return self.multiplier == float(other)
69 def __ne__(self, other):
70 return not self.__eq__(other)
72 def __lt__(self, other):
73 return self.multiplier < float(other)
75 def __gt__(self, other):
76 return self.multiplier > float(other)
78 def __le__(self, other):
79 return self < other or self == other
81 def __ge__(self, other):
82 return self > other or self == other
85 return self.multiplier
87 def __repr__(self, *, relative=False, places=3):
89 percentage = (self.multiplier - 1.0) * 100.0
91 percentage = self.multiplier * 100.0
92 return f'{percentage:+.{places}f}%'