1

I have been trying to make a function that takes a series of numbers and outputs its cumulative maximum with a decay factor.

So for example, if I have this:

my_series = np.array([5, 3.6, 4.1, 2.3, 1.7, 4.9, 3.6, 6.4, 4.5])
decay_factor = 0.991

The desired output of my function would be the following:

[5.         4.955      4.910405   4.86621135 4.82241545 4.9
 4.8559     6.4        6.3424    ]

As you can see, every new element must be the greatest between the next element from my original series and the previous element from the output series multiplied by the decay factor.

I would love to be able to make this function without using any for loops, so that I can speed it up.

debpj
  • 11
  • 1
  • 1
    I don't think for loop is avoidable in this case. You can try `numpa` to accelerate the loop. – Quang Hoang Apr 03 '21 at 01:26
  • 2
    i think you mean ```numba``` – Kevin Apr 03 '21 at 01:53
  • `cummax` is actually `add.accumulate`. `np.maximum.accumulate` does what you want, but without the decay. There is a loop, but it's in compiled code. A pure Python loop, working from a list, will be faster than anything using non-compiled `numpy`. – hpaulj Apr 03 '21 at 03:51
  • I don't think you can do it without for loops under the hood. The closest you probably can get with an implicit for loop is something similar to [this](https://stackoverflow.com/a/28915456/10961342) post using `itertools.accummelate`. In your case that would be `list(accumulate(my_series, lambda x, y: x * decay_factor if y < x else y))`. Or `np.array` instead of `list`. – Thymen Apr 04 '21 at 00:19

0 Answers0