Skip to content
Course contents
Getting started with Python

Calculating with code

Python is a calculator that never tires, and this chapter uses its arithmetic to compute something a trader cares about, a trade's profit and return, introducing operators and the order they apply in.

8 min readChapter 5 of 30
What you will learn
  • Use arithmetic operators and understand operator precedence
  • Compute a simple return or position value in code
  • Store and reuse a computed result

At heart a computer is a calculator that never tires and never slips, and now that you can store values in variables, you can put it to work on numbers that matter to a trader. This chapter takes a trade from its prices to its profit and its percentage return, entirely in code, and in doing so introduces the arithmetic operators and the order in which Python applies them. It is a small program, but it is the first that computes something genuinely useful.

The operators

An expression is evaluated by precedence, so multiplication happens before addition: 2 + 3 * 4 is 14, not 20.
An expression is evaluated by precedence, so multiplication happens before addition: 2 + 3 * 4 is 14, not 20.

Python's arithmetic looks much as you would expect. A plus sign adds, a minus subtracts, an asterisk multiplies, and a forward slash divides. You combine values and variables into an expression, like buy_price * quantity, and Python works out its value. Expressions can be as long as you like, and Python follows the usual rules of precedence: multiplication and division happen before addition and subtraction, and you can use brackets to force a different order or simply to make your intent clear. When in doubt, add brackets; they cost nothing and they prevent a whole category of quiet mistakes.

A trade, computed step by step

Here is a complete little program that takes a buy price, a quantity, and a sell price, and works out what you invested, what you received, your profit, and your percentage return.

ExampleFrom prices to profit and return, one step at a timech05/position_value.py
# From prices to profit and return, one step at a time.
buy_price = 1400
quantity = 10
invested = buy_price * quantity      # total cost

sell_price = 1540
proceeds = sell_price * quantity     # total received

profit = proceeds - invested
return_pct = profit / invested * 100

print(f"Invested: {invested}")
print(f"Proceeds: {proceeds}")
print(f"Profit: {profit}")
print(f"Return: {return_pct:.2f}%")
Output
Invested: 14000
Proceeds: 15400
Profit: 1400
Return: 10.00%

The output walks through the trade: an invested amount of 14000, proceeds of 15400, a profit of 1400, and a return of 10.00%. Follow how it was built. First invested is computed as buy_price * quantity, 1400 times 10, giving 14000. Then proceeds is sell_price * quantity. The profit is simply proceeds - invested, and the return_pct divides that profit by what you invested and multiplies by 100 to turn it into a percentage. Each line computes one value and stores it in a well-named variable, and later lines use those stored results rather than repeating the arithmetic. Building a calculation up in named steps like this, rather than cramming it into one dense line, is a habit that keeps code readable and easy to check.

Notice the :.2f inside the last line's output. That is a small piece of formatting that tells Python to show the number to two decimal places, so you get a tidy 10.00% rather than a long string of digits. You met f-strings in passing already, and the next part covers this kind of formatting properly; for now, just know that is what rounds the display.

An honest footnote on the number

The 10% this program reports is a clean, textbook return, and it is worth a word of honesty that connects back to the earlier courses. It is the return before any costs and before any tax. As the Taxation and Risk and Psychology courses showed, the brokerage, the securities transaction tax, and the other charges come off every real trade, and tax comes off the profit, so the amount you actually keep is smaller than the headline figure. The arithmetic here is exactly right; it simply answers the gross question. When you build real analysis later in the course, remembering to subtract costs is part of being honest with your own numbers. This is education, not advice.

What to carry forward

Python is a tireless, exact calculator: you combine values into expressions with the arithmetic operators, it follows the usual precedence, and brackets let you control the order. Building a calculation in named, reusable steps, as the trade program did from invested and proceeds to profit and return, keeps code clear and checkable. And keep the honest footnote in mind: a computed return is the gross figure, while the amount kept is after costs and tax.

That completes the first part, the setup and the absolute basics. Part 2 builds the core of the language itself, starting with how Python handles text, the strings you will use for tickers, labels, and the tidy reporting of every result.