Back
Learning Hub/ Python for Algo Trading/ Lesson 5 Phase 1 of 6
Python for Algo Trading · Phase 1

Lists — Ordered Collections

Candle arrays. Trade history. Watchlists. Every algo system works with sequences of data. Python's list is the most versatile data structure for storing, slicing, and processing ordered collections of prices and trade records.

Lesson 5 of 9 ~40 min Intermediate OHLC candle arrays
Lesson 5 of 9 — Lists56% complete
LESSON 05 · SECTION 1
What is a List?
intermediate

A list is an ordered, mutable collection of items enclosed in square brackets. Items are accessed by index starting from 0. Lists can hold any type — prices, strings, other lists — and grow/shrink dynamically.

📋
Ordered
Items stay in insertion order. prices[0] is always the first price you added.
✏️
Mutable
You can add, remove, or change items after creation. Essential for live candle buffers.
🔢
Zero-indexed
list[0] = first, list[-1] = last. Negative indexes count from the end.
🌀
Mixed types
A list can hold integers, floats, strings, even other lists (2D arrays for OHLC).
list_basics.pypython
closes   = [22300, 22360, 22440, 22410, 22500]
watchlist = ["NIFTY", "BANKNIFTY", "RELIANCE", "TCS"]

print(closes[0])     # 22300 — first item
print(closes[-1])    # 22500 — last item
print(len(closes))   # 5 — number of items
print(max(closes))   # 22500 — highest close
print(min(closes))   # 22300 — lowest close
print(sum(closes))   # 112010 — sum
Output
22300
22500
5
22500
22300
112010

Section 2
Slicing — Extract Candle Windows

Slicing extracts a sub-list using [start:stop:step]. In algo trading, slicing is how you extract the last N candles to calculate a moving average or detect patterns.

slicing.pypython
closes = [22100, 22200, 22300, 22380, 22440, 22410, 22500]

print(closes[2:5])    # [22300, 22380, 22440] — index 2 to 4
print(closes[-3:])    # [22440, 22410, 22500] — last 3 candles
print(closes[::2])    # every other candle

# 3-period Simple Moving Average on last 3 closes
last3 = closes[-3:]
sma3  = sum(last3) / len(last3)
print(f"SMA(3) = {sma3:.1f}")

# 5-period SMA
last5 = closes[-5:]
sma5  = sum(last5) / len(last5)
print(f"SMA(5) = {sma5:.1f}")
Output
[22300, 22380, 22440]
[22440, 22410, 22500]
[22100, 22300, 22440, 22500]
SMA(3) = 22450.0
SMA(5) = 22406.0

Section 3
List Methods for Trading
MethodWhat it doesTrading use
append(x)Add item to endAppend new tick/candle to buffer
pop()Remove & return last itemRemove oldest candle (FIFO buffer)
remove(x)Remove first matchRemove exited stock from watchlist
sort()Sort in placeSort stocks by P&L
reverse()Reverse in placeFlip candle order oldest→newest
count(x)Count occurrencesCount BUY signals in history
index(x)Find positionFind where a price level was last seen
list_methods.pypython
# Rolling 5-candle buffer
candle_buffer = [22100, 22200, 22300, 22380, 22440]
new_candle    = 22500

# Add new, remove oldest
candle_buffer.append(new_candle)
candle_buffer.pop(0)
print("Buffer:", candle_buffer)

# Signal history
signals = ["BUY", "HOLD", "BUY", "SELL", "BUY", "HOLD"]
print("BUY signals:", signals.count("BUY"))

# Watchlist management
watchlist = ["NIFTY", "BANKNIFTY", "RELIANCE"]
watchlist.append("TCS")
watchlist.remove("BANKNIFTY")
print("Watchlist:", watchlist)
Output
Buffer: [22200, 22300, 22380, 22440, 22500]
BUY signals: 3
Watchlist: ['NIFTY', 'RELIANCE', 'TCS']

Section 4
2D Lists — OHLC Candle Arrays

A 2D list is a list of lists. This is the natural structure for OHLC candle data — each inner list is one candle with [open, high, low, close, volume].

ohlc_2d.pypython
# NIFTY 5-min OHLCV — [open, high, low, close, volume]
ohlcv = [
    [22300, 22380, 22270, 22360, 125000],
    [22360, 22400, 22320, 22340, 98000],
    [22340, 22450, 22330, 22440, 143000],
    [22440, 22480, 22390, 22410, 112000],
    [22410, 22510, 22400, 22500, 165000],
]

# Extract all close prices
closes  = [c[3] for c in ohlcv]
highs   = [c[1] for c in ohlcv]
volumes = [c[4] for c in ohlcv]

print(f"Closes      : {closes}")
print(f"Session High: ₹{max(highs)}")
print(f"Avg Volume  : {sum(volumes)//len(volumes):,}")

# Latest candle
latest = ohlcv[-1]
print(f"\nLatest Candle:")
print(f"  O={latest[0]} H={latest[1]} L={latest[2]} C={latest[3]}")
Output
Closes      : [22360, 22340, 22440, 22410, 22500]
Session High: ₹22510
Avg Volume  : 128600

Latest Candle:
  O=22410 H=22510 L=22400 C=22500

Section 5
SMA Calculator with Lists

Using list slicing, we can compute a rolling Simple Moving Average — the foundation of dozens of trading strategies.

sma_calculator.pypython
def sma(prices, period):
    """Simple Moving Average over last N periods"""
    if len(prices) < period:
        return None
    window = prices[-period:]
    return round(sum(window) / period, 2)

closes = [22100, 22200, 22300, 22380, 22440,
          22410, 22500, 22480, 22520, 22560]

sma5  = sma(closes, 5)
sma10 = sma(closes, 10)
ltp   = closes[-1]

print(f"LTP   : ₹{ltp}")
print(f"SMA5  : ₹{sma5}")
print(f"SMA10 : ₹{sma10}")

if sma5 > sma10:
    print("📈 SMA5 > SMA10 — Bullish crossover")
else:
    print("📉 SMA5 < SMA10 — Bearish crossover")
Output
LTP   : ₹22560
SMA5  : ₹22494.0
SMA10 : ₹22389.0
📈 SMA5 > SMA10 — Bullish crossover
💡 PRO TIP
In production systems, you'd use pandas or numpy for SMA calculations on large datasets. But understanding the list-based version first makes you a better trader-developer — you know what's happening under the hood.

Section 6
Quick Quiz
QUESTION 1 OF 3
Given closes = [22100, 22200, 22300], what does closes[-1] return?
A22100
B22200
C22300
DIndexError
QUESTION 2 OF 3
What does closes[-3:] return from a 7-item list?
AThe first 3 items
BThe last 3 items
CItems at index 3, 4, 5
DAn error
QUESTION 3 OF 3
Which method correctly implements a rolling FIFO buffer (add new, remove oldest)?
Abuf.add(x); buf.remove(x)
Bbuf.append(x); buf.pop(0)
Cbuf.push(x); buf.shift()
Dbuf.insert(0, x); buf.pop()

Section 7
Practice Exercises
EXERCISE 1 · EASY
Session Statistics
Given closes = [22300, 22360, 22440, 22410, 22500, 22480, 22520], print the session high, low, average, and range (high - low) using list functions.
Hint: use max(), min(), sum()/len().
EXERCISE 2 · MEDIUM
Rolling 3-Period SMA
Write a function that takes a list of closes and a period, and returns a new list of SMA values. For candles before the period, append None. Test with a 10-candle close list and period=3.
Hint: use slicing closes[i-period+1:i+1] inside a for loop.
EXERCISE 3 · CHALLENGE
Trade History Manager
Maintain a list of trade dicts [{sym, side, entry, exit, pnl}]. Write functions to: (1) add a trade, (2) get total P&L, (3) get the best and worst trade by P&L.
Hint: use max(trades, key=lambda t: t['pnl']) for best trade.
🚀 UP NEXT — LESSON 6
Lists store ordered sequences. But what if you want to access trade data by name (e.g., trade["symbol"]) instead of index? Lesson 6: Dictionaries — the data structure that powers trade objects, config files, and API responses.
Prev