How do I compare lists of tickers and count repeats?

Find the stocks that entered and left an index with set differences, check whether two groups overlap with isdisjoint, count trades per stock with Counter, and remove repeats in order.

After this lesson, you can compare two lists of tickers and count how often each stock traded.

Which stocks entered or left the index?

A set holds each item once, in no fixed order, so set(trades) turns a list of trades into the stocks traded. Subtracting one set from another keeps the items of the first that the second lacks. FFF and GGG entered the index between March and June, and DDD and EEE left it. & keeps the items in both sets.

The trades are a made-up fund’s purchases in an index on two dates, one ticker per trade, and the fund buys every member and only members. sorted() returns a set’s items as an alphabetical list for printing. .isdisjoint() returns True when two sets share no item, which checks, for example, that a model is tested on companies it was not fitted on.

The following box compares the two dates.

march_trades = ["BBB", "AAA", "BBB", "CCC", "BBB", "AAA", "DDD", "CCC", "BBB", "EEE"]
june_trades = ["AAA", "BBB", "CCC", "FFF", "GGG"]
march = set(march_trades)
june = set(june_trades)
print(sorted(june - march), sorted(march - june), sorted(june & march))
print(march.isdisjoint(june - march))
['FFF', 'GGG'] ['DDD', 'EEE'] ['AAA', 'BBB', 'CCC']
True

ticker in march tests membership faster than ticker in march_trades, because a set finds an item without reading the whole list.

How do I count the trades per stock?

Counter(march_trades) counts each ticker, and .most_common(2) returns the two most frequent with their counts. BBB traded four times in March, and AAA and CCC twice each.

The following box counts the March trades.

from collections import Counter

counts = Counter(march_trades)
print(counts.most_common(2), counts["FFF"])
[('BBB', 4), ('AAA', 2)] 0

A Counter returns zero for a ticker it never saw, such as FFF.

How do I remove repeats and keep the order?

list(dict.fromkeys(trades)) keeps each ticker once in the order it first appears, because a dictionary holds each of its keys once and keeps them in the order they were added. A set removes the repeats but forgets the order.

The following box removes the repeats both ways.

print(sorted(set(march_trades)), list(dict.fromkeys(march_trades)))
['AAA', 'BBB', 'CCC', 'DDD', 'EEE'] ['BBB', 'AAA', 'CCC', 'DDD', 'EEE']

BBB, the first trade of March, comes first in the second list.

Your turn

Print each ticker traded on both dates with its total number of trades over both lists, in alphabetical order. You should see AAA 3, BBB 5 and CCC 3.

+ joins the two lists, so the Counter counts every trade.

both_counts = Counter(march_trades + june_trades)
for ticker in sorted(march & june):
    print(ticker, both_counts[ticker])
AAA 3
BBB 5
CCC 3