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

Comparing Neighbors With pairwise()

00:00 In this lesson, you’ll load seventy years of stock market data and turn daily prices into daily percent changes with pairwise(). Here’s your challenge. Find the biggest daily gain, the biggest daily loss, and the longest growth streak in the history of the S and P 500 stock market index.

00:20 The data is in a CSV file with one row per trading day, from 1950 to 2018. You’ll use the date column and the adjusted closing price. You can download the file from the course materials.

00:33 You’ll need to compare values that belong to dates, so start with a small class. Import namedtuple from the collections module. DataPoint is a named tuple with a date and a value.

00:46 Its three comparison methods compare only the values, so you can use less than, greater than, and the built-in max() and min() on data points. Setting __slots__ to an empty tuple keeps each data point as lightweight as a plain tuple.

01:01 So when you call max() on data points, you get the day with the biggest value. Next, read the file. The csv module reads each row as a dictionary, and datetime parses the dates.

01:17 read_prices() is a generator. For each row, it yields a DataPoint with the date and the adjusted close.

01:31 Collect the prices in a tuple, since you’ll need to go over them more than once. The first data point is from January third, 1950. To get a daily percent change, you need two neighboring days at a time: yesterday and today.

01:46 pairwise() gives you exactly that. It slides a window of two along the data. First it yields day one and day two, then day two and day three, then day three and day four.

01:57 Each pair overlaps the one before, and each pair becomes one percent change. pairwise() arrived in Python 3.10. Four letters give you three overlapping pairs.

02:09 For every pair of neighboring days, the gain is the percent change from the previous day’s price to the current one. Before pairwise() existed, you’d zip the prices with a slice of themselves, which only works on sequences.

02:23 There are about seventeen thousand trading days, and one gain fewer than prices, since the first day has no day before it. In this lesson, you loaded the S and P 500 prices and turned them into daily gains with pairwise().

02:38 You stored the gains in a tuple on purpose. You’ll go over them twice, once for the maximum and once for the minimum, and a tuple uses no more memory than tee() would in that case.

02:49 Next up, you’ll find the biggest gain and the biggest loss.

Become a Member to join the conversation.