Loops and Conditions
Loops
Loops are a fundamental programming concept, allowing you to execute a chunk of code multiple times. This is particularly useful in finance, where you might need to process data over several periods or perform repetitive calculations. A common use case is backtesting. Essentially, it is about simulating a past trading or investment strategy by looping through each price from a specific time period. We will look into this topic in detail towards the end of the course.
Python primarily uses two types of loops: for
and while
.
for
loop in Python
The The for
loop lets you iterate through a sequence, executing a block of code for each element in the sequence. Sequences can be various types such as lists, tuples, dictionaries, or strings, which we will dive into later.
Let us say you have a bank balance of $3000, a monthly salary of $2000, and monthly expenses totaling $1800. You want to calculate your balance at the end of the year (after 12 months). Here is how you might use a for
loop to solve this:
balance = 3000
salary = 2000
expenses = 1800
for i in range(12):
balance = balance + salary - expenses
print("Balance after", i+1, "months", balance, "€")
print("My account balance at the end of the year is:", balance, "€")
In this example, we start by setting up three variables: balance
, monthly_salary
, and monthly_expenses
. These variables represent the starting balance, monthly salary, and monthly expenses, respectively.
Next, we use a for
loop to model the transactions over 12 months. The range(12)
function creates a sequence of numbers from 0 to 11 (12 elements in total).
Inside the loop, we update our balance by adding the monthly salary and subtracting the monthly expenses. The print()
function is used to output the balance for each month.
You may notice that the two lines below for
are not aligned at the same level. Indeed, they are indented, meaning they are spaced 4 spaces to the left. The indented lines are included within the for
loop, whereas non-indented lines like the last one are not. In practice, this means the display "Balance after..."
will be shown 12 times, whereas the text "My account balance..."
will only be displayed once.
With this little code, we update our balance by adding our salary and deducting our expenses, and use the print()
function to show our new balance as well as the current month. As we previously mentioned, the range(12)
function generates a sequence of numbers from 0 to 11, so we add 1 to i when displaying the month, to start from month 1 instead of month 0. Lastly, we display the balance at the end of the year. When you run the code, you should get something like this:
while
loop in Python
The The while
loop executes a block of code as long as a certain condition remains true. For instance, let's calculate how long it will take to double an investment at a fixed annual interest rate:
initial_investment = 1000
years = 0
interest_rate = 0.05
current_value = initial_investment
while current_value < initial_investment * 2:
current_value = current_value * (1 + interest_rate)
years += 1
print("It will take", years, "years to double the investment.")
In this example, the code block inside the while
loop will be executed until the current_value
is at least double the initial investment. With each iteration, we update current_value
by adding the interest, and increment years
by 1.
We exit the while loop when the value of current_value
becomes greater than twice our initial investment. At this point, we use the print
function to display the value of our years
variable, which represents the number of years needed to double our investment.
How to use conditions in python
Conditions are essential in programming. They allow you to execute a specific block of code if a condition is met, and possibly a different block of code if it is not. In Python, you use the keywords if
, elif
, and else
to handle these conditions. if
stands for if, elif
for else if, and else
is used when conditions are not met.
Have a look at this simple example:
bitcoin_price = 45000
if bitcoin_price <= 30000:
print("Buy")
elif bitcoin_price > 30000 and bitcoin_price <= 50000:
print("Sell half")
elif bitcoin_price < 60000:
print("Hold")
else:
print("Sell all")
In this example, the program prints "Sell half" since the bitcoin_price
is 45,000, which is greater than 30,000 but less than 50,000. Note the use of and
here; it is a logical operator. There is also an or
operator.
Here are a few more examples of using conditions:
text = "hello"
if text == "hello" or text == "hi":
print("text is hello or hi")
elif text != "hello":
print("text is neither hello nor hi")
condition = True
if condition is True:
print("My condition is true")
else:
print("My condition is false")
Note that we have used the operator !=
which stands for not equal to.
Try to guess what this code will output before running it 😉.
Example: combining loops and conditions in Python
Let us consider an example where we use both loops and conditions. Imagine you want to figure out how long it will take to reach a savings goal, considering you might get a raise at work.
- Savings goal: €10,000
- Savings per month: €400
- Expected raise in 6 months
- Extra savings per month after raise: €200 (Total €600 per month)
# Variables
savings_goal = 10000
monthly_savings = 400
month_of_raise = 6
raise_amount = 200
# Counter Initialization
months_required = 0
total_savings = 0
# Loop until you reach the savings goal
while total_savings < savings_goal:
# Check if the raise is in effect and adjust monthly savings
if months_required == month_of_raise:
monthly_savings += raise_amount
# Update total savings
total_savings += monthly_savings
# Increment the months counter
months_required += 1
print(f"You will need {months_required} months to reach your savings goal of €{savings_goal}.")
In this example, we are using a while
loop to simulate the process of saving money every month, and checking whether we have hit our savings target. Inside the loop, there is an if
statement that checks if a pay raise has kicked in and adjusts the monthly savings accordingly. We are also using a counter called months_needed
to keep tabs on how many months it is taking to reach our savings goal.
Next, we keep our balance updated by adding in the monthly salary and taking out the expenses, and then we display the updated balance using the print()
function. Alongside, we show which month of the year it is. One thing to remember is that the range(12)
function creates a sequence of numbers starting from 0 to 11, so while displaying the month, we add 1 to i
to make sure the count starts at month 1 and not month 0.
At the end of it all, we display the balance we have accumulated by the year's end.
Take note of the +=
operator. Essentially, a += 1
is shorthand for a = a + 1
. The +=
operator adds the value on its right to the variable on the left, and then assigns the result back to the variable on the left. There are similar operators like -=
and *=
. Have a try:
a = 5
a += 3 # a = a + 3
print(a) # Displays 8
b = 10
b -= 1 # b = b - 1
print(b) # Displays 9
c = 2
c *= 15 # c = c * 15
print(c) # Displays 30
Putting it all into practice
Let us dive in and apply the concepts we have discussed in this section by tackling a straightforward exercise. Picture this—you have invested 1,000 Euros in a mix of financial assets, and you are re curious to find out how many years it will take for your investment to hit a certain target.
Let’s assume you have the following information:
- Initial investment: 1000 Euros
- Capitalization goal: 2000 Euros
- Annual interest rate: 4%
Questions:
- How many years are we talking about to hit that target?
- Tinker with the annual interest rate and observe how it shifts the timeline.
- Throw in a
for
loop to experiment with a range of annual interest rates (say, from 2% to 8%, stepping up by 1%) and display how the number of years stacks up for each rate.
This hands-on exercise should give you a firmer grasp on employing loops and conditional statements in Python, especially in a finance setting. A correction example can be found here: https://github.com/RobotTraders/Python_For_Finance/blob/main/exercise_correction_chapter_2.ipynb. Do not hesitate to customize this scenario to suit your own intrigue and delve into other financial what-ifs.