Quant500 Academy

4. Control flow: loops and list comprehensions

Level 2: Python from Scratch for Finance

Any trading strategy is, at heart, a chain of decisions of the form 'if this happens, do that'. In Python those decisions are written with if, elif (short for 'else if') and else.

current_price = 183.20
moving_average = 180.00

if current_price > moving_average:
    print("Buy signal: price is above the moving average")
elif current_price == moving_average:
    print("No signal: price is exactly at the average")
else:
    print("Sell signal: price is below the moving average")

Here we meet one of Python's most distinctive traits, and one that surprises anyone coming from another language: blocks of code are not delimited with curly braces {}, they are delimited by indentation. Everything indented by the same number of spaces belongs to the same block. If you get the indentation wrong, Python raises a syntax error outright rather than producing an unexpected result — one of its most useful protections, however awkward it feels at first.

To repeat an action over each element of a sequence you use the for loop, the tool you will use most for iterating over lists of prices, tickers or dates.

week_prices = [182.52, 184.10, 179.88, 181.45, 183.20]

for price in week_prices:
    if price > 183:
        print(f"High price detected: {price}")

When you need both the value and its position in the list, enumerate gives you both at once, instead of having to keep a manual counter:

for day, price in enumerate(week_prices):
    print(f"Day {day}: {price}")

The while loop, by contrast, repeats as long as a condition holds, no matter how many times — useful, for example, to simulate a position until the stop-loss triggers:

capital = 10000
day = 0

while capital > 5000 and day < 30:
    capital = capital * 1.01  # simulated growth of 1% per day
    day += 1

print(f"Simulation finished on day {day}, final capital: {capital:.2f}")

A construct very characteristic of Python, and one you will see constantly in real financial code, is the list comprehension: a compact way of creating a new list by applying an operation to each element of another, in a single line instead of a full for loop.

daily_returns = [(week_prices[i] - week_prices[i-1]) / week_prices[i-1]
                  for i in range(1, len(week_prices))]

That single line computes the percentage return of each day relative to the previous one, running through the whole list. It is exactly the same result as writing a for loop with an empty list you keep appending to, but shorter and, in most cases, faster to run.

The rest of Quant500

What you are learning, applied to the index every day:

The model portfolio, weekly in your inbox

Every Saturday, its week in one minute: how it went, the best and the worst, and which insiders bought with their own money. Plus, the day the model is rebuilt, which stocks come in and which go out. A simulation, not advice. At most one email a week, no ads, no account; one-click unsubscribe. Made by one person: Pol Gracia.

A model portfolio with simulated results, not a personalized recommendation. Your email is used for this only: privacy.

Behind the Academy and the rest of Quant500 there is one person: Pol Gracia Serrahima.