Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Finding the Biggest Gain and Loss

00:00 In this lesson, you’ll find the biggest daily gain and loss in the S and P 500 data with reduce() and filterfalse(), and you’ll avoid a subtle bug along the way.

00:11 The reduce() function from functools works a lot like accumulate(), except that it only returns the final value. Import functools with the short name ft.

00:23 Reducing the gains with max() gives you the biggest gain: more than eleven and a half percent, in October 2008. That works, but there’s a hidden problem.

00:36 Imagine that the data showed a loss on every single day. Then reduce() would still return the largest value, which would be the smallest loss. You’d report a loss as your biggest gain, and that’s a hard bug to spot.

00:49 filterfalse() helps here. It takes a function that returns True or False, called a predicate, and keeps the items for which the predicate is false. Drop everything that’s zero or less, and only the positive numbers remain.

01:04 But if every value is negative, then nothing is left, and reduce() raises a TypeError. Give reduce() an initial value of zero as its third argument, and if every day is a loss, you now get zero.

01:18 Here’s the pipeline. The gains flow in. filterfalse() drops every day that isn’t a gain. Then reduce() walks through what’s left and keeps the larger of each pair, until one champion remains.

01:30 If nothing makes it through the filter, then the initial value is the answer. Now apply that to the stock market data. Create a zero data point to compare against and to use as the initial value.

01:44 For the maximum gain, filter out every day that’s zero or less, and reduce with max(). For the maximum loss, flip it around. Filter out the gains, and reduce with min().

01:58 The biggest gain was 11.58 percent, in October 2008. And the biggest loss was minus 20.47 percent, on the nineteenth of October 1987, known as Black Monday.

02:14 In this lesson, you combined reduce() and filterfalse() to find the extremes in the data, with an initial value to guard against empty inputs. Next up, you’ll find the longest run of consecutive gains with takewhile() and dropwhile().

Become a Member to join the conversation.