⚠ Trading involves significant risk of loss. Everything on this site is for education only and is not financial advice.
Lesson 2 of 13 · Free

Python Essentials for Finance in One Session: Data Types, Lists, Dictionaries, Loops, Functions and Error Messages

Learn the minimum core Python a trader needs: numbers, strings, lists, dictionaries, loops, functions and how to read a traceback.

Author: Moustafa HijaziContent reviewed: 2026-10-305 min readSelf-study course

What you will learn

  • The data types you will meet in price data: int, float, str, bool, None and datetime.
  • How lists and dictionaries store a trade list, and how a for loop processes it.
  • How to write a function with a docstring and a default argument, and why functions make backtests testable.
  • How to read a Python traceback from the bottom up and fix the five most common errors.

Explanation

Types. Every value in Python has a type. 42 is an int (whole number), 42.5 a float (decimal number stored in binary), "AAPL" a str (text), True a bool, and None means "no value". Floats are approximate (0.1 + 0.2 prints 0.30000000000000004), so never compare them with ==; use round() or a tolerance. For dates use pandas timestamps (lesson 3).

Lists are ordered collections written with square brackets: closes = [100.0, 102.0, 101.5]. Indexing starts at zero (closes[0] is 100.0), negative indices count from the end (closes[-1] is the latest close), and slicing closes[1:3] returns elements 1 and 2 but not 3. The same end-excluded rule applies to pandas iloc.

Dictionaries map keys to values: trade = {"symbol": "AAA", "entry": 50.0, "qty": 100}. Access with trade["entry"]; a missing key raises KeyError, while trade.get("fee", 0.0) returns a default.

Loops and conditions. A for loop visits each element: for t in trades: followed by an indented block. Indentation (four spaces) defines the block. if, elif and else branch on conditions, and comparison operators are ==, !=, <, >=.

Functions package logic so it can be reused and tested. The keyword def starts a definition, parameters go in brackets, and return sends a value back:

def r_multiple(entry, exit_price, stop, side="long"):

'''Return profit in units of initial risk (R).'''

risk = abs(entry - stop)

pnl = exit_price - entry if side == "long" else entry - exit_price

return pnl / risk

The triple-quoted string is a docstring (documentation), and side="long" is a default argument. Keep functions small, explicit about their inputs and free of side effects; that is what lets lesson 9 unit-test them.

Reading errors. When something fails, Python prints a traceback. Read the last line first: it names the error type and message. Then look at the line just above it, which shows where in your code it happened. The most common errors: NameError (you used a variable before defining it, often because a notebook cell was not run); TypeError (for example adding a string from a CSV file to a number, fix with float()); KeyError (a column or dictionary key is spelled differently, check for spaces and capital letters); IndexError (you asked for element 10 of a list with 10 elements, remember zero-based indexing); and ZeroDivisionError (a stop equal to the entry gives risk zero).

Worked example

Hypothetical example: three closed long trades, all in euros, commissions and taxes ignored.

trades = [

{"symbol": "AAA", "entry": 50.0, "exit": 53.0, "stop": 48.0, "qty": 100},

{"symbol": "BBB", "entry": 20.0, "exit": 19.0, "stop": 19.0, "qty": 250},

{"symbol": "CCC", "entry": 80.0, "exit": 78.0, "stop": 76.0, "qty": 60},

]

total = 0.0

for t in trades:

pnl = (t["exit"] - t["entry"]) * t["qty"]

r = r_multiple(t["entry"], t["exit"], t["stop"])

total += pnl

print(t["symbol"], pnl, round(r, 2))

print("Total:", total)

AAA profit = (53 − 50) × 100 = €300; risk per share €2, so R = 3 ÷ 2 = 1.5. BBB = (19 − 20) × 250 = −€250; risk €1 per share, R = −1.0 (stopped out exactly). CCC = (78 − 80) × 60 = −€120; risk €4, R = −0.5. Total = 300 − 250 − 120 = −€70. Output lines: AAA 300.0 1.5, BBB -250.0 -1.0, CCC -120.0 -0.5, Total: -70.0.

total += pnl is shorthand for total = total + pnl. Three trades say nothing about a method; the point is the mechanics.

Common mistake

Running notebook cells out of orderNotebooks run cells in any order. Edit the trades list, rerun only the loop cell, and a stale value silently feeds a result; after a kernel restart you get NameError instead. Before trusting any number, use "Restart kernel and run all cells" and make sure it runs top to bottom without error.

Practice activity

On paper, write a function position_size(account, risk_pct, entry, stop) that returns the whole number of shares (rounding down) and raises a clear ValueError if the stop equals the entry. Then write the result for account €8,000, risk 1.25%, entry €32.50, stop €30.00. Finally, name the error type Python would raise if you called the function with entry="32.50" (a string) and did not convert it.

Show solution

def position_size(account, risk_pct, entry, stop):

per_share = abs(entry - stop)

if per_share == 0:

raise ValueError("stop must differ from entry")

return int(account * risk_pct // per_share)

Numbers: risk budget = 8,000 × 0.0125 = €100; per-share risk = 32.50 − 30.00 = €2.50; 100 ÷ 2.50 = 40 shares exactly, so the function returns 40 (planned risk €100, position value €1,300).

With entry="32.50", the expression "32.50" - 30.0 raises TypeError: unsupported operand type(s) for -: 'str' and 'float'. Convert with float(entry).

Limitations: the function ignores minimum lot sizes, commissions and the fact that a gap can lose more than the planned €100.

Key takeaways

  • Floats are approximate, indexing starts at zero and slices exclude the end; these three facts prevent most beginner bugs.
  • A list of dictionaries is the natural shape for trades before pandas; loops process it, functions give it reusable logic.
  • Write small, pure functions with docstrings; they are the units you will test in lesson 9.
  • Read tracebacks from the bottom up, and restart-and-run-all before trusting a notebook result.

Next step

Lesson 3 introduces pandas: Series, DataFrames, the DatetimeIndex, selecting and filtering rows, and turning daily bars into weekly bars with resample.

Self-check

Answer the questions, then check your answers. You can retry as often as you like.

1. Given closes = [100.0, 102.0, 101.5, 103.0], what does closes[1:3] return?

2. A loop over a trade list crashes with KeyError: 'Exit'. Which is the most likely cause and fix?

3. Using the r_multiple function from the lesson for a short trade: entry €40.00, stop €42.00, exit €35.00. What does it return?

Automatic self-check for your own revision. Your answers are checked in your browser and are not seen or assessed by us. It is not an exam and not a qualification.

Your progress

“Complete” only means you marked the lesson as done. It is not a test of your understanding. Progress and notes are saved only in this browser on this device — not in an account.