How do I sort records and find a value in a sorted list fast?
Sort trades by any field with sorted and a key, and find where a time falls in a sorted list with bisect, which halves the search at every step.
After this lesson, you can sort trades by any field and count the trades at a time in a sorted list.
How do I sort trades by different fields?
sorted(trades) returns a new list in ascending order, and key= tells it what to compare in each row. Sorting by time puts the 09:30 trade first, and key=lambda trade: trade[2], reverse=True puts the largest trade, 900 shares, first.
The trades are made-up trades of one day, each a tuple of time, ticker and shares. Python compares tuples field by field, so two trades at 10:00 are ordered by ticker. A lambda is a short function, as in the lesson on functions. .sort() sorts the list itself and returns None, while sorted() keeps the original order available.
The following box sorts the trades by time and by size.
The two trades of 300 shares keep their original order, because sorted leaves ties as they were.
Where does a time belong in a sorted list?
bisect.bisect_left(times, "10:00") returns the first position whose time is at or after 10:00, and bisect.bisect_right the first position after it, so their difference counts the trades at 10:00, here 2. Both search by halving the list, so a million sorted times take at most 20 comparisons.
The list must be sorted. Text times sort in time order because they all have two digits for the hour. Neither call changes the list.
The following box prints both boundaries and the count for three times.
import bisecttimes = [trade[0] for trade in by_time]for target in ["09:00", "10:00", "10:10"]: left = bisect.bisect_left(times, target) right = bisect.bisect_right(times, target)print(target, left, right, right - left)
09:00 0 0 0
10:00 2 4 2
10:10 4 4 0
For 10:10, both boundaries are 4, the position where a trade at 10:10 would fit, so no trade has that time.
Your turn
Use the two boundaries for 10:00 to print the ticker and shares of each trade at 10:00. You should see AAA 400 and BBB 300.
TipShow answer
by_time[left:right] takes the trades between the boundaries, because times came from the same sorted rows.
left = bisect.bisect_left(times, "10:00")right = bisect.bisect_right(times, "10:00")for time, ticker, shares in by_time[left:right]:print(ticker, shares)