Course contents
Packaging logic to reuse
A function is a named, reusable piece of logic that takes inputs and returns a result, so you write the calculation once, a return, say, and call it everywhere. Functions are how programs stay organised as they grow.
- Define a function with parameters and a return value
- Call a function and use its result
- Write a small function that computes a return or a signal
As programs grow, you find yourself writing the same calculation again and again, the percentage return, say, computed in three different places. Copying it around is how bugs breed: fix it in one place, forget the others, and now your program disagrees with itself. The cure is the function, a named piece of logic you write once and call wherever you need it. Functions are how a program stays organised and trustworthy as it gets bigger, and they are worth reaching for the moment a calculation repeats.
Defining and calling a function
You define a function with def, a name, and a list of inputs called parameters, and inside it you compute something and hand back a result with return. Then you call the function by name, passing in values, and use whatever it returns. This program defines two small functions and reuses them.
# A function packages logic so you write it once and reuse it.
def simple_return(buy, sell):
"""Percentage return from a buy price to a sell price."""
return (sell - buy) / buy * 100
print(f"{simple_return(1400, 1540):.2f}%")
print(f"{simple_return(3120, 3050):.2f}%")
def is_profit(buy, sell):
return sell > buy
print("Trade 1 profit?", is_profit(1400, 1540))
print("Trade 2 profit?", is_profit(3120, 3050))10.00% -2.24% Trade 1 profit? True Trade 2 profit? False
The first function, simple_return, takes a buy price and a sell price and returns the percentage return between them. Defined once, it is called twice, on 1400 and 1540 to give 10.00%, and on 3120 and 3050 to give -2.24%, and it would work on any pair of prices you pass. The text in triple quotes just under the def is a docstring, a short note saying what the function does, which is good manners and helps the reader. The second function, is_profit, returns a boolean, True or False, showing that a function can hand back an answer to a yes-or-no question just as easily as a number: the two calls report True for the winning trade and False for the losing one.
Why functions matter
Two benefits make functions essential rather than optional. The first is reuse: the return calculation lives in exactly one place, so if you ever need to change it, to subtract costs, for instance, you change it once and every caller gets the improvement. The second is clarity: a well-named function like simple_return reads like a sentence at the point you call it, hiding the arithmetic behind a name that says what it does, so your main program describes what is happening rather than how. As your trading programs grow to fetch data, compute indicators, and test rules, functions are what keep them from collapsing into an unreadable tangle.
A good habit follows from this: when you notice yourself writing the same few lines a second time, stop and make them a function. Named, tested once, and reused, that logic becomes a reliable building block instead of a phrase you keep re-typing and re-breaking.
What to carry forward
A function packages logic behind a name: you define it with def and parameters, hand back a result with return, and call it wherever needed, whether it returns a number like a percentage return or a boolean like a profit check. Functions give you reuse and clarity, the two things that keep a growing program from turning into a tangle, so make a function as soon as a calculation repeats.
Functions assume their inputs are sensible, but real market data often is not: a symbol is missing, a value is blank, a divisor is zero. The next chapter shows how to handle those failures gracefully instead of crashing.