Join us and get access to thousands of tutorials and a community of expert Pythonistas.
This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.
Finding the Longest Growth Streak
00:00 In this lesson, you’ll find the longest run of consecutive gains in the S and P 500 data with takewhile() and dropwhile(). Both functions take a predicate and an iterable.
00:13 takewhile() yields items as long as the predicate is true, and stops at the first item where it’s false. dropwhile() does the opposite. It skips items while the predicate is true, then yields everything from there on.
00:27 Combine the two, and you can cut a sequence into streaks. Picture the gains as plus and minus days, with one shared iterator moving along them. First, dropwhile() skips the losses.
00:38 Then takewhile() collects the run of gains that follows, until it hits the next loss. That’s one streak. Because the iterator is shared, the next pass picks up exactly where the last one stopped.
00:51 When the iterator runs dry, you get an empty tuple, and that’s the signal to stop. Here’s that idea as code. The trick is repeat(). It hands out the same iterator over and over, so each loop pass continues where the previous one stopped.
01:07 dropwhile() skips the losses, and takewhile() collects the gains into a tuple. The outer takewhile() stops at the first empty tuple. Test it on a short list, and you get three streaks of positive numbers.
01:21 That’s one and two, then three on its own, then four, five, and six. Now run it on the real data. Call it with the gains, and use the zero data point as the threshold.
01:32 reduce() keeps whichever streak is longer.
01:38 Grab the first and last dates of that streak.
01:43 The longest growth streak lasted fourteen trading days, from late March to mid-April 1971. In this lesson, you composed takewhile(), dropwhile(), and repeat() to split the gains into streaks, and you found the longest one.
01:59 That completes the S and P 500 challenge. Next up, you’ll meet groupby() and help a swim team pick its relay teams.
Become a Member to join the conversation.