-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path11_advanced_data_structures.py
More file actions
67 lines (50 loc) · 2.29 KB
/
Copy path11_advanced_data_structures.py
File metadata and controls
67 lines (50 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""
11_advanced_data_structures.py
------------------------------
Concept: Advanced Data Structures (Deque, Heapq, NamedTuple, Sets)
Context: Efficient Order Books, Sliding Windows, and Unique Symbol management.
"""
from collections import deque, namedtuple
import heapq
# 1. Deque (Double-ended Queue)
# Perfect for "Sliding Windows" where we only care about the last N items.
print("--- 1. Deque: Sliding Window for SMA ---")
price_window = deque(maxlen=5) # Only keeps the most recent 5 prices
# Simulating incoming price stream
stream_prices = [100, 102, 101, 103, 104, 106, 108]
for p in stream_prices:
price_window.append(p)
avg = sum(price_window) / len(price_window)
print(f"Added ${p} | Window: {list(price_window)} | SMA: {avg:.2f}")
# 2. Heapq (Priority Queue)
# Perfect for an Order Matching Engine where the 'Best' price must be accessed first.
# Bids: Highest price is best. (We store negatives to use min-heap as max-heap)
# Asks: Lowest price is best.
print("\n--- 2. Heapq: Order Matching Engine ---")
sell_orders = [] # Min-heap (Standard)
heapq.heappush(sell_orders, (105.50, "Order_A")) # Price, ID
heapq.heappush(sell_orders, (105.20, "Order_B"))
heapq.heappush(sell_orders, (106.00, "Order_C"))
print(f"Sell Orders Heap: {sell_orders}")
# Getting the best ask (lowest price)
best_ask = heapq.heappop(sell_orders)
print(f"Matched/Filled Best Ask: {best_ask}")
print(f"Remaining Order Book: {sell_orders}")
# 3. Sets
# Perfect for storing UNIQUE items, like a list of supported symbols
print("\n--- 3. Sets: Unique Symbols ---")
exchange_a_symbols = ["BTC", "ETH", "SOL", "ADA"]
exchange_b_symbols = ["BTC", "ETH", "DOT", "MATIC"]
unique_assets = set(exchange_a_symbols)
unique_assets.update(exchange_b_symbols) # Adds only new ones
print(f"All Unique Assets: {unique_assets}")
# Set operations: What is common to both?
common = set(exchange_a_symbols).intersection(exchange_b_symbols)
print(f"Arbitrage Opps (Common Symbols): {common}")
# 4. NamedTuple
# specific structure for immutable data, like a Trade Record
print("\n--- 4. NamedTuple: Trade Records ---")
Trade = namedtuple('Trade', ['symbol', 'price', 'qty', 'side'])
t1 = Trade('BTC/USDT', 60000, 0.5, 'BUY')
print(f"Trade Detail: {t1.side} {t1.qty} {t1.symbol} @ ${t1.price}")
# t1.price = 61000 # Error! Immutable. Safer for logs.