Calculating the percentage different between integers in a list

0 39
Avatar for JZA
Written by
4 years ago

For people that have been doing coding on the market, this might be a common task that they have to do to calculate the behavior of the market. Having a percentage between one element and the next help us see whenever we can do backtrades strategies. So for that this function seems important. One of the challenges I have found is that in Python lists are not unmutable, which means that they could change order and that can break our dependency on it. For that Python has a nifty function called zip().

If we go to the python documentation, zip is:

Make an iterator that aggregates elements from each of the iterables.

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.

So here is a function with a sample list:

prices = [30.4, 32.5, 31.7, 31.2, 32.7, 34.1, 35.8, 37.8, 36.3, 36.3, 35.6]

for a, b in zip(prices[::1], prices[1::1]):

print 100 * (b - a) / a

1
$ 0.00

Comments