print(2 + 3) # -> 5
print(10 - 4) # -> 6
print(6 * 7) # -> 42
print(9 / 2) # -> 4.5
print(2 ** 10) # -> 1024 <- ** is "to the power of"5
6
42
4.5
1024
Python does maths with +, -, *, / and ** for powers, and brackets decide what happens first, exactly as on paper. An f-string, written f"...", drops a value into text: anything inside {} gets worked out and printed.
I show the operators first, then the profit on one trade, then the return written as a percentage with commission taken off both legs.
Each line prints one calculation.
5
6
42
4.5
1024
/ gives a decimal even when the numbers divide evenly, so 10 / 5 is 2.0, not 2.
Multiplication happens before addition. Brackets change that.
I buy 40 shares at 150.00 and sell them at 168.75. The profit is the price change times the number of shares.
750.0
Drop the brackets and Python multiplies before it subtracts.
print(profit) gives the bare number. An f-string puts it in a sentence.
Bought 40 shares at 150.0
Cost: 6000.0 USD
The part after a colon inside the braces formats the number. :,.2f means two decimals with a thousands separator.
The return on the trade is the sell price over the buy price, minus one.
ret holds 0.125, a decimal. The :.2% code multiplies by 100 and adds the sign when it prints.
The broker charges 0.10% of the traded value, on the buy and on the sell. 0.10% written as a decimal is 0.001.
6.0
6.75
12.75
Take the fees off the profit and divide by the cost of the shares.
net_profit = profit - fee_total
net_ret = net_profit / value
print(f"Gross profit: {profit:,.2f} USD") # -> Gross profit: 750.00 USD
print(f"Commission: {fee_total:,.2f} USD") # -> Commission: 12.75 USD
print(f"Net profit: {net_profit:,.2f} USD") # -> Net profit: 737.25 USD
print(f"Gross return: {ret:.2%}") # -> Gross return: 12.50%
print(f"Net return: {net_ret:.2%}") # -> Net return: 12.29%Gross profit: 750.00 USD
Commission: 12.75 USD
Net profit: 737.25 USD
Gross return: 12.50%
Net return: 12.29%
12.75 USD of commission moves the return from 12.50% to 12.29%.
I buy 120 shares at 92.50 and sell them at 88.25. The same broker charges 0.10% on each leg. Print the profit, the return, the commission, and the return after commission, all with two decimals.
buy = 92.50
sell = 88.25
shares = 120
value = buy * shares
profit = (sell - buy) * shares
ret = sell / buy - 1
fee_total = (buy * shares + sell * shares) * 0.001 # both legs
net_profit = profit - fee_total
net_ret = net_profit / value
print(f"Profit: {profit:,.2f} USD") # -> Profit: -510.00 USD
print(f"Return: {ret:.2%}") # -> Return: -4.59%
print(f"Commission: {fee_total:,.2f} USD") # -> Commission: 21.69 USD
print(f"Net profit: {net_profit:,.2f} USD") # -> Net profit: -531.69 USD
print(f"Net return: {net_ret:.2%}") # -> Net return: -4.79%