Skip to content
🐍Trade Logic with if/elif/else

Trade Logic with if/elif/else

beginner Python 10 minifelifelse
What you'll learn
  • if
  • elif
  • else
  • comparison operators
  • P&L

Control Flow - P&L Classification

Scene: 4:59pm, the market is about to close. Your portfolio manager leans over: "Quick - which of our positions are winning and which are bleeding? Don't eyeball it. Flag them." Four tickers, four entry prices, four live prices. You could squint and do mental arithmetic - or write six lines of Python that classify every position, today and every day, for a 4-name book or a 500-name book. This is control flow: teaching your code to make decisions.

Every position manager needs to flag trades: is this a winner, a loser, or flat?

How the decision logic works

🧠 The mental model: one turnstile, first True wins

An if/elif/else ladder is a turnstile with several gates - exactly one gate opens, and it is the FIRST one whose condition is True. Python walks the ladder top-down:

  1. Test the if condition. True? Run that block and skip everything below.
  2. False? Fall through to the next elif and test again.
  3. Nothing was True? The else catches whatever is left - it has no condition because it is the fallback.

Two consequences every trader's code lives by:

  • Order matters. If two conditions overlap, the one written first wins - the later one never even gets checked.
  • The else is a catch-all. Here it catches the knife-edge case where the return is exactly zero.

Conditional Syntax

Python
if condition:
    # runs when condition is True
elif other_condition:
    # runs when first was False but this is True
else:
    # fallback - runs when all above are False

Comparison operators - the vocabulary of trading rules

OperatorReads asTrading example
>strictly greaterpct_return > 0 - position is up
<strictly lesspct_return < 0 - position is down
>= / <=at least / at mostdrawdown <= -20 - bear-market threshold hit
==equal (a test - NOT the assignment =)rating == "AAA"
!=not equalstatus != "FILLED" - order still working

⚠️ > and < are strict: a return of exactly 0 is neither > 0 nor < 0. That is precisely why the ladder needs its else.

Threshold-Based Risk Flags

In systematic trading, conditions drive automated decisions:

Python
if pnl_pct > 0.10:
    action = "TAKE_PROFIT"   # lock in gains
elif pnl_pct < -0.05:
    action = "STOP_LOSS"     # cut losses
else:
    action = "HOLD"          # do nothing

πŸ“œ The History of Stop-Losses - Why Rules Replace Emotions

The stop-loss rule - "exit a position when loss exceeds X%" - sounds mechanical, but it took catastrophic failures to make it standard practice.

Jesse Livermore (1907, 1929): The legendary speculator who made and lost four fortunes on Wall Street. Reminiscences of a Stock Operator (1923), Edwin Lefèvre's thinly veiled account of his career, describes his discovery that "the big money was never made in the buying and the selling - but in the waiting." More crucially, he identified that failure to cut losses early was the single biggest cause of ruin for speculators. He violated his own rules in 1940 and took his own life.

The 1987 Black Monday crash (βˆ’22.6% in one day): Portfolio insurance strategies - which used if/else logic to sell futures when prices fell below thresholds - were blamed for amplifying the crash. The feedback loop: falling prices triggered sell rules, which drove prices lower, which triggered more sell rules. The first systemic demonstration that automated conditional logic at scale can destabilise markets.

LTCM (1998): Long-Term Capital Management held positions for months without stop-losses, trusting their models. When spreads kept widening instead of converging, they had no exit rule. The Federal Reserve organised a $3.6 billion bailout. Partners included Nobel laureates Myron Scholes and Robert Merton.

The lesson every risk manager internalises: if/else conditions must exist before you enter a trade, not after it starts losing.


One line of given scaffolding: the for loop

Your rules will live inside this line, which is written for you (you write your own loops in the very next lesson - today just read this one):

Python
for ticker, entry_price, current_price in portfolio:

Read it as: "deal the positions off the book one at a time; for each one, put its three fields into the names ticker, entry_price and current_price, then run my indented rules on them." Everything indented under that line executes once per position - which is why your if/elif/else ladder must stay indented inside it.

Your Task

The starter code already loops through the book and computes each % return - but the classification line is a lazy placeholder that stamps βš–οΈ FLAT on every trade, so the desk summary reports zero winners and zero losers. Replace that one line with an if/elif/else ladder assigning βœ… WIN / ❌ LOSS / βš–οΈ FLAT, and the summary will come alive.

Predict before you run: GS is down just 0.31% - barely a scratch. Which flag should it get? If you said FLAT, look at the ladder again: > and < are strict, so the else only catches a return of exactly zero. "Nearly flat" is still a loss. Decide how many winners and losers the summary should report out of the 4 positions - then run and check yourself.