CoCalc Shared FilesWeek 03 Lab / CDS-102 Week 03 Lab.ipynb
Authors: James Glasbrenner, concorde habineza
Views : 6
Description: Jupyter notebook Week 03 Lab/CDS-102 Week 03 Lab.ipynb

# CDS-102 Week 3: Functions, Loops, and Conditionals

Name: Full name here

Due: September 19, 2016 by 11:00am

## Introduction

In this week's lab, we continue with learning about the fundamentals of using Sage for computational work. Whereas last week we focused on becoming more familiar with the interface of Jupyter notebooks and the basic syntax and features of Sage, in this lab we will practice three important concepts from programming. These are functions, loops, and conditionals, and they are available for use in Sage thanks to its Python base. These concepts show up all the time in computational science work (and programming in general) and they are important building blocks of software. Despite the rather complicated logical structures one can build using these tools, these concepts are relatively simple to understand. So if you've never worked with these before, do not worry! It's all about practice and trying ideas out.

## Reference

### Function structure

An example of the general structure for defining a function is:

def functionname(input1, input2, ...):
<body>


Note that there is a 4-space indent for the <body> field.

### For loop structure

The structure of a for loop is:

for <var> in <sequence>:
<body>


Note that there is a 4-space indent for the <body> field. The for loop completes once the full sequence has been iterated over.

### if/else conditional structure

The structure of the if/else conditional statement is:

if <condition>:
<statements>
else:
<statements>


Note that there is a 4-space indent for the <statements> field.

The <condition> must evaluate to either True or False. This is done by writing mathematical comparisons in the <condition> field, such as 50 > 20 (True), 100 <= 50 (False), and 25 == 25 (True). If the <condition> is True, then the <statements> under if are run. If it's False, then the <statements> under else are run.

### while loop structure

The structure of a while loop is:

while <condition>:
<body>


Note that there is a 4-space indent for the <body> field. The while loop will continue indefinitely as long as the <condition> field evaluates to True. Once it evaluates as False, the loop stops.

## Your first piece of software: a simple investment calculator

Congratulations! You've just been hired to work at ABC Banking Corp as a software engineer. Unlike most of today's banks, ABC Banking Corp has been slow to adopt new technology, meaning that they've been doing all their banking using paper and desk calculators. You've been tasked with bringing them into the 21st century by developing software that can automate their banking needs.

Your first assignment is to develop software that can assist their banking representatives with calculating investments. One of the financial products that ABC Banking Corp offers to its customers is a 10-year certificate of deposit (CD) with an annual interest rate of 1%. This CD is an example of a financial product with compounding interest. Your task is to create a function named cdapr that contains a for loop that will take the initial principal (the customer's deposit) and calculate the value of the CD by the end of the 10-year period.

In the event that you remember the compounding interest formula from another class (it contains the exponential $e$), assume in this scenario that you've forgotten the formula (this exercise will demonstrate that an algorithmic approach to a calculation can simplify the math).

Hint: Let $P$ be the value of the initial deposit and $r$ be the interest rate. After one year, the value of the investment will be $P_{\text{1yr}} = P \left( 1 + r \right)$. After two years, the value of the investment will be $P_{\text{2yr}} = P_{\text{1yr}} \left( 1 + r \right)$, and so on.

### Exercise 1 (10 pts)

In the code box below, define a function named cdapr that takes a single input, the initial principal, and then calculates the value of the CD after 10 years. Run the code box when you are done.

Hint: The final line of your cdapr function needs to output the final value of the investment. Use the print function to do this. For example, the following function:

def myfunction(num):
print num


will print out the supplied number. Running myfunction(10.5) will output

10.5000000000000

In [ ]:



### Exercise 2 (5 pts)

In the code box below, use the cdapr function that you defined above to calculate the value of the CD when you start with the following principals:

• $100 •$5200
• $35000 In [ ]:   ### Exercise 3 (10 pts) Your manager is happy to see that your software is already working as described. However, work doesn't end. The bank offers many different CD investment options, and each one has a different interest rate and number of years for the investment period. Your manager wants you to modify the function to take two additional inputs, the interest rate and the number of years for the CD investment, and edit the code so that the function calculates the value of the investment given the supplied principal, interest rate, and the number of years of the investment. Copy your cdapr function into the code box below to use as a starting point, rename it cdapr_v2, and implement the specified modifications. Run the code box when you are done. In [ ]:   ### Exercise 4 (5 pts) Now let's test that the modified function works as intended. Use cdapr_v2 to calculate the following investments (the first one tests that you still get the same output as in Exercise 2): • Principal =$100, interest rate = 1%, years = 10
• Principal = $3000, interest rate = 2.2%, years = 5 • Principal =$5000, interest rate = 10%, years = 30
In [ ]:



### Exercise 5 (10 pts)

Your manager is very pleased so far with your progress. She has now informed you that many of ABC Banking Corp's CD's will be moving to an alternative to the annual interest rate, so another modification for your function is needed. The alternative will be to calculate the accrued interest in terms of a nominal interest rate and a specified number of compounding periods. So, for example, instead of a 1% annual rate compounded annually, the interest might be compounded quarterly. This means the account would earn 0.25% interest every 3 months instead of 1% each year.

Copy your cdapr_v2 into the code box below to use as a starting point, rename it cdapr_v3, and implement the specified modifications. The function should take as input the starting principal, the annual interest rate, the number of compounding periods per year, and the number of years of the investment. Run the code box when you are done.

In [ ]:



### Exercise 6 (5 pts)

Use cdapr_v3 to calculate the following investments:

• Principal = $3000, annual interest rate = 2.2%, compounding periods per year = 4, years = 5 • Principal =$7500, annual interest rate = 4.2%, compounding periods per year = 12, years = 10
• Principal = $7500, annual interest rate = 8.1%, compounding periods per year = 12, years = 30 In [ ]:   ### Exercise 7 (15 pts) In Exercise 4 and Exercise 6 you calculated an investment with a starting principal of$3000, an annual interest rate of 2.2%, and an investment period of 5 years, but one was compounded annually and the other quarterly. What interest rate compounded annually in function cdapr_v2 would you need to have to get the same investment return for the cdapr_v3 function that was compounded quarterly? Explain how you determined this.

Hint: Use the "trial-and-error" approach by using a while loop that checks whether the two values are close enough. The basic algorithm would be to guess an interest rate, compare it with the anually compounded calculation, and if the difference between the two calculations does not fall within a reasonable tolerance (the two outputs should be accurate within a fraction of a penny, at least), change the interest rate and try again.

In [ ]:



### Exercise 8 (10 pts)

ABC Banking Corp also offers retirement investment accounts where customers can deposit a fixed amount of money per year that gets added to their total principal, which is then compounded at a fixed annual interest rate. Your manager wants you to modify the cdapr_v2 function to calculate and output the value of a retirement account so that they can pitch these to potential customers.

Copy your cdapr_v2 function into the code box below, rename it retirement, and implement the specified modifications. The variable you used to specify the initial principal will now be the amount of money deposited per year by the customer. Run the code block when you are done.

Hint: The yearly deposit should be added to the principal before calculating the interest. The account should also start with $\text{principal} = 0$ before the first deposit.

In [ ]:



### Exercise 9 (5 pts)

Use the retirement function you just defined to calculate the final value of the following retirement accounts:

• Yearly deposit = $3000, interest rate = 2%, years = 20 • Yearly deposit =$2100, interest rate = 3.7%, years = 30
• Yearly deposit = $3500, interest rate = 5.5%, years = 40 In [ ]:   ### Exercise 10 (10 pts) Your manager has one more assignment for you before you can leave for the day. The retirement accounts do not operate for free, ABC Banking Corp collects annual fees from the accounts as part of their service. However, they do not start charging the annual fee until a retirement account has at least$50000. Furthermore, the annual fee, which is 0.8%, is only applied to the dollars added to the principal above the $50000 threshold. Finally, the fee is calculated after the yearly deposit but before the annual interest is added in. The annual interest is also calculated after the yearly deposit but before the annual fee is collected. For example, say a retirement account has$55000, the yearly deposit is $2500, and the annual interest rate is 5%. The calculations would proceed as follows: • Annual interest: (55000 + 2500) * 0.05 = 2875 • Annual fee: (55000 + 2500 - 50000) * 0.008 = 60 • Retirement account after fees collected and interest added: 55000 + 2500 + 2875 - 60 = 60315 Copy your retirement function into the code box below, name it retirement_v2, and implement the fee structure described above. Create an input for the annual fee so that you can change it from 0.8%. Round the final result to the nearest penny. Run the code block when you are done. Hint: You will have to use an if/else conditional statement when calculating the fees. In [ ]:   ### Exercise 11 (5 pts) Using the retirement_v2 function you just defined, recalculate the final value of the retirement accounts specified in Exercise 9. How much does each retirement account pay total in fees when compared with the fee-less calculations? In [ ]:   ### Exercise 12 (10 pts) Your manager is about to close up, but you want to see if you should do your own retirement investments through ABC Banking Corp or through their competitor CDE Investors Lmtd. Each has a retirement account where, if you make an annual deposit of$3500 for 40 years, you'll get an annual interest rate of 5.5%. The fees at CDE Investors Lmtd. are calculated in the same way as ABC Banking Corp, except because of computational automation CDE Investors Lmtd. is able to charge a lower 0.4% annual fee. However, CDE Investors Lmtd. is an hour drive from your home and each deposit to the retirement account must be done in person, so you're not sure if it's worth the effort to save just 0.4% in fees. But, thanks to your function, you can figure out how much you'd save.

Using the retirement_v2 function, calculate what your final investment value would be when the annual fees are reduced to 0.4%. How much would you save? Do you think this amount of savings would make traveling an hour to CDE Investors Lmtd. worth it?

In [ ]: