Financial leverage could be easily described as the tool that allows traders to multiply returns at the cost of multiplying also the risk involved in every trade. So, for instance, if a stock today costs 10\$ and tomorrow it appreciates up to 11\$, the trader would experience a return of: $$ R = (\frac{11}{10} -1)*100 = 10\% $$
While, by using a leverage of - let's say 2x - the return would still be: $$ R = (\frac{22}{20} -1)*100 = 10\% $$
But of course in absolute terms, after having given back the borrowed 10\$ from the broker, the trader would experience twice the return. 2\$ instead of just 1\$.
Now, my question is: how this kind of phenomena could be described programmatically, let's say in Python? I found out that even if I could theoretically describe how leverage works, I fail to algorithmically think of it.
Let's say that I have a black box that produces trading signals: $$ \boldsymbol{\tau} = \{1, 2, 3, 4\} \\ $$
where: $$ 1:= Sell \ with \ 10x \ leverage \\ 2:=Sell \ with \ no \ leverage \\ 3 := Buy \ with \ no \ leverage \\ 4 := Buy \ with \ 10x \ leverage$$
I started implementing Python code to depict such an algorithm. How could it be completed implementing leverage?
if signal == 1:
#Sell with 10x leverage
if stock_holdings > 0:
# Code here
elif signal == 2:
#Sell with no leverage
if stock_holdings > 0:
USD_holdings = stock_holdings * stock_price
stock_holdings = 0
elif signal == 3:
#Buy with no leverage
if USD_holdings > 0:
stock_holdings = USD_holdings / stock_price
USD_holdings = 0
elif signal == 4:
#Buy with 10x leverage
if USD_holdings > 0:
# Code here