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

Loops — For & While

Scanning a 50-stock watchlist. Iterating over 200 daily candles. Running a live tick loop. All of this is powered by loops. Master for and while with real NSE watchlist scanning and candle analysis examples.

Lesson 3 of 9 ~40 min Beginner–Intermediate NSE Watchlist examples
Lesson 3 of 9 — Loops: For & While33% complete
LESSON 03 · SECTION 1
Why Loops?
beginner

Without loops, checking 50 stocks would require 50 separate if blocks. A loop lets you repeat a block of code — once per stock, once per candle, or until a condition changes. Python has two loop types: for (fixed iterations) and while (condition-based).

🔁
for loop
Iterates over a sequence (list, range, string). Perfect for scanning watchlists or candle arrays.
while loop
Repeats while a condition is True. Ideal for live monitoring loops that run until market close.
⏭️
break & continue
break exits the loop early. continue skips to the next iteration.
🔢
range()
Generates a sequence of numbers. range(5) gives 0,1,2,3,4. Very useful with for.

Section 2
The for Loop

A for loop steps through each item in a collection. In trading, you use it to process every stock in a watchlist or every candle in an OHLC dataset.

for_loop_basics.pypython
# Scan a NSE watchlist
watchlist = ["RELIANCE", "TCS", "INFY", "HDFCBANK", "ICICIBANK"]

for stock in watchlist:
    print(f"Checking signal for: {stock}")

# range() — iterate 5 times
print("\n--- Candle index ---")
for i in range(5):
    print(f"Candle #{i}")

# enumerate() — index + value
print("\n--- With index ---")
for idx, stock in enumerate(watchlist):
    print(f"{idx+1}. {stock}")
Output
Checking signal for: RELIANCE
Checking signal for: TCS
Checking signal for: INFY
Checking signal for: HDFCBANK
Checking signal for: ICICIBANK

--- Candle index ---
Candle #0
Candle #1
Candle #2
Candle #3
Candle #4

--- With index ---
1. RELIANCE
2. TCS
3. INFY
4. HDFCBANK
5. ICICIBANK

Section 3
Watchlist Scanner with Signals

Combine the for loop with if/else to build a real watchlist scanner that checks every stock against its VWAP and generates signals.

watchlist_scanner.pypython
# Watchlist Scanner — LTP vs VWAP
stocks = [
    {"name": "RELIANCE", "ltp": 2945, "vwap": 2880},
    {"name": "TCS",      "ltp": 3820, "vwap": 3890},
    {"name": "INFY",     "ltp": 1480, "vwap": 1480},
    {"name": "HDFCBANK", "ltp": 1565, "vwap": 1520},
    {"name": "WIPRO",    "ltp": 460,  "vwap": 472},
]

print(f"{'STOCK':12} {'LTP':>8} {'VWAP':>8} {'SIGNAL':>10}")
print("-" * 42)

for s in stocks:
    if s["ltp"] > s["vwap"]:
        signal = "✅ BUY"
    elif s["ltp"] < s["vwap"]:
        signal = "🔴 SELL"
    else:
        signal = "⏸ HOLD"
    print(f"{s['name']:12} {s['ltp']:>8} {s['vwap']:>8} {signal:>10}")
Output
STOCK           LTP     VWAP     SIGNAL
------------------------------------------
RELIANCE       2945     2880     ✅ BUY
TCS            3820     3890    🔴 SELL
INFY           1480     1480     ⏸ HOLD
HDFCBANK       1565     1520     ✅ BUY
WIPRO           460      472    🔴 SELL

Section 4
break & continue

break immediately exits the loop — useful when you find the first BUY signal and don't need to scan further. continue skips the rest of the current iteration — useful to ignore stocks with zero volume.

break_continue.pypython
prices = [22100, 22050, 22380, 22450, 22310]
vwap   = 22300

# break — stop at first price above VWAP
print("--- First VWAP cross ---")
for i, price in enumerate(prices):
    if price > vwap:
        print(f"VWAP cross at index {i}, price ₹{price}")
        break
    print(f"  Index {i}: ₹{price} — below VWAP")

# continue — skip zero-volume ticks
volumes = [1200, 0, 3400, 0, 2100]
print("\n--- Skip zero volume ---")
for i, vol in enumerate(volumes):
    if vol == 0:
        continue   # skip this tick
    print(f"Tick {i}: volume = {vol}")
Output
--- First VWAP cross ---
  Index 0: ₹22100 — below VWAP
  Index 1: ₹22050 — below VWAP
VWAP cross at index 2, price ₹22380

--- Skip zero volume ---
Tick 0: volume = 1200
Tick 2: volume = 3400
Tick 4: volume = 2100

Section 5
The while Loop

The while loop keeps running as long as a condition is True. In live trading systems, the main event loop is a while True that checks for signals every second until market close.

while_loop.pypython
# Simulated tick monitor — while loop
import random

ltp        = 22300
target     = 22500
stop_loss  = 22100
ticks      = 0

print("Starting tick monitor...")

while stop_loss < ltp < target:
    # Simulate price movement
    ltp += random.randint(-30, 40)
    ticks += 1
    print(f"  Tick {ticks:02d}: LTP = ₹{ltp}")
    if ticks >= 8:   # safety cap for demo
        break

if ltp >= target:
    print(f"\n🎯 Target ₹{target} hit! Exiting trade.")
elif ltp <= stop_loss:
    print(f"\n🛑 Stop Loss ₹{stop_loss} hit! Exiting trade.")
else:
    print(f"\n⏱ Demo cap reached. LTP: ₹{ltp}")
⚠️ INFINITE LOOP RISK
A while True loop without a break or exit condition will run forever and crash your system. Always include a break condition (e.g., market hours check or kill switch).

Section 6
Candle Analysis — Loop over OHLC

OHLC data is a list of candles. Loop over it to find patterns, calculate highs/lows, or detect specific candle formations like bullish engulfing.

candle_analysis.pypython
# NIFTY 5-min candles [open, high, low, close]
candles = [
    [22300, 22380, 22270, 22360],
    [22360, 22400, 22320, 22340],
    [22340, 22450, 22330, 22440],
    [22440, 22480, 22390, 22410],
    [22410, 22510, 22400, 22500],
]

session_high = 0
session_low  = 999999
bullish      = 0
bearish      = 0

for i, c in enumerate(candles):
    o, h, l, close = c
    session_high = max(session_high, h)
    session_low  = min(session_low, l)
    candle_type  = "🟢 Bull" if close > o else "🔴 Bear"
    if close > o: bullish += 1
    else: bearish += 1
    print(f"Candle {i+1}: O={o} H={h} L={l} C={close}  {candle_type}")

print(f"\nSession High : ₹{session_high}")
print(f"Session Low  : ₹{session_low}")
print(f"Bullish/Bearish: {bullish}/{bearish}")
Output
Candle 1: O=22300 H=22380 L=22270 C=22360  🟢 Bull
Candle 2: O=22360 H=22400 L=22320 C=22340  🔴 Bear
Candle 3: O=22340 H=22450 L=22330 C=22440  🟢 Bull
Candle 4: O=22440 H=22480 L=22390 C=22410  🔴 Bear
Candle 5: O=22410 H=22510 L=22400 C=22500  🟢 Bull

Session High : ₹22510
Session Low  : ₹22270
Bullish/Bearish: 3/2

Section 7
List Comprehension — Compact Loops

Python's list comprehension creates a new list by running a loop in a single line. Ideal for filtering stocks, normalising price data, or extracting close prices from candles.

list_comprehension.pypython
prices = [22300, 22360, 22440, 22410, 22500]

# Extract close prices from candles
candles = [[22300,22380,22270,22360], [22360,22400,22320,22340],
           [22340,22450,22330,22440]]
closes = [c[3] for c in candles]
print("Close prices:", closes)

# Filter stocks above VWAP (2880)
ltps  = {"RELIANCE":2945, "TCS":3820, "INFY":1480, "WIPRO":460}
vwaps = {"RELIANCE":2880, "TCS":3890, "INFY":1460, "WIPRO":472}

buy_list = [sym for sym in ltps if ltps[sym] > vwaps[sym]]
print("BUY candidates:", buy_list)

# Percentage change from entry
entry = 22300
pct_changes = [round((p - entry) / entry * 100, 2) for p in prices]
print("% Changes:", pct_changes)
Output
Close prices: [22360, 22340, 22440]
BUY candidates: ['RELIANCE', 'INFY']
% Changes: [0.0, 0.27, 0.63, 0.49, 0.9]
💡 PRO TIP
List comprehensions are 2–3× faster than equivalent for loops for large datasets — important when processing thousands of ticks per second.

Section 8
Quick Quiz
QUESTION 1 OF 3
Which keyword immediately stops a loop when a target price is hit?
Acontinue
Bbreak
Creturn
Dstop
QUESTION 2 OF 3
What does [c[3] for c in candles] produce?
AA list of open prices
BA list of high prices
CA list of close prices (index 3)
DAn error — candle has no index 3
QUESTION 3 OF 3
A while True loop without a break or exit condition will:
ARun exactly 100 times then stop
BReturn None automatically
CRun forever — causing a hang or crash
DRaise a SyntaxError

Section 9
Practice Exercises
EXERCISE 1 · EASY
Sum of Close Prices
Given closes = [22360, 22340, 22440, 22410, 22500], use a for loop to calculate the total and average close price. Print both results.
Hint: initialise total = 0 before the loop, then divide by len(closes).
EXERCISE 2 · MEDIUM
Highest Volume Stock
Given a dict of stocks and their volumes, loop through and find the stock with the highest volume. Use volumes = {"RELIANCE": 1500000, "TCS": 980000, "INFY": 1200000, "WIPRO": 750000}.
Hint: track a max_vol = 0 and top_stock = "" variable inside the loop.
EXERCISE 3 · CHALLENGE
Consecutive Green Candles
Write a loop over the candle list from Section 6. Count the maximum number of consecutive bullish candles (close > open). Print the count and which candle index it started on.
Hint: track current_streak and max_streak variables. Reset current_streak on a bearish candle.
🚀 UP NEXT — LESSON 4
You can now iterate. But copy-pasting the same logic for different symbols wastes code. Lesson 4: Functions teaches you to wrap reusable logic into clean, callable blocks — the foundation of every modular algo trading system.
Prev