{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"# CDS-102 Week 3: Functions, Loops, and Conditionals"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Name:** Full name here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Due:** September 19, 2016 by 11:00am"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Introduction"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Reference"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Function structure\n",
"\n",
"An example of the general structure for defining a function is:\n",
"\n",
"```python\n",
"def functionname(input1, input2, ...):\n",
" \n",
"```\n",
"\n",
"Note that there is a 4-space indent for the `` field."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### `For` loop structure\n",
"\n",
"The structure of a `for` loop is:\n",
"\n",
"```python\n",
"for ` in :\n",
" \n",
"```\n",
"\n",
"Note that there is a 4-space indent for the `` field. The `for` loop completes once the full sequence has been iterated over."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### `if/else` conditional structure\n",
"\n",
"The structure of the `if/else` conditional statement is:\n",
"\n",
"```python\n",
"if :\n",
" \n",
"else:\n",
" \n",
"```\n",
"\n",
"Note that there is a 4-space indent for the `` field.\n",
"\n",
"The `` must evaluate to either `True` or `False`. This is done by writing mathematical comparisons in the `` field, such as `50 > 20` (`True`), `100 <= 50` (`False`), and `25 == 25` (`True`). If the `` is `True`, then the `` under `if` are run. If it's `False`, then the `` under `else` are run."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### `while` loop structure\n",
"\n",
"The structure of a `while` loop is:\n",
"\n",
"```python\n",
"while :\n",
" \n",
"```\n",
"\n",
"Note that there is a 4-space indent for the `` field. The `while` loop will continue indefinitely as long as the `` field evaluates to `True`. Once it evaluates as `False`, the loop stops."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Your first piece of software: a simple investment calculator"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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. \n",
"\n",
"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.\n",
"\n",
"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).\n",
"\n",
"**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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 1 *(10 pts)*\n",
"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.\n",
"\n",
"**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:\n",
"\n",
"```python\n",
"def myfunction(num):\n",
" print num\n",
"```\n",
"\n",
"will print out the supplied number. Running `myfunction(10.5)` will output\n",
"```\n",
"10.5000000000000\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 2 *(5 pts)*\n",
"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:\n",
"\n",
"- \\$100\n",
"- \\$5200\n",
"- \\$35000"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 3 *(10 pts)*\n",
"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.\n",
"\n",
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 4 *(5 pts)*\n",
"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):\n",
"\n",
"- Principal = \\$100, interest rate = 1%, years = 10\n",
"- Principal = \\$3000, interest rate = 2.2%, years = 5\n",
"- Principal = \\$5000, interest rate = 10%, years = 30"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 5 *(10 pts)*\n",
"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.\n",
"\n",
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 6 *(5 pts)*\n",
"Use `cdapr_v3` to calculate the following investments:\n",
"\n",
"- Principal = \\$3000, annual interest rate = 2.2%, compounding periods per year = 4, years = 5\n",
"- Principal = \\$7500, annual interest rate = 4.2%, compounding periods per year = 12, years = 10\n",
"- Principal = \\$7500, annual interest rate = 8.1%, compounding periods per year = 12, years = 30"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 7 *(15 pts)*\n",
"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.\n",
"\n",
"**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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 8 *(10 pts)*\n",
"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.\n",
"\n",
"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.\n",
"\n",
"**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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 9 *(5 pts)*\n",
"Use the `retirement` function you just defined to calculate the final value of the following retirement accounts:\n",
"\n",
"- Yearly deposit = \\$3000, interest rate = 2%, years = 20\n",
"- Yearly deposit = \\$2100, interest rate = 3.7%, years = 30\n",
"- Yearly deposit = \\$3500, interest rate = 5.5%, years = 40"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 10 *(10 pts)*\n",
"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.\n",
"\n",
"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:\n",
"\n",
"- Annual interest: `(55000 + 2500) * 0.05 = 2875`\n",
"- Annual fee: `(55000 + 2500 - 50000) * 0.008 = 60`\n",
"- Retirement account after fees collected and interest added: `55000 + 2500 + 2875 - 60 = 60315`\n",
"\n",
"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.\n",
"\n",
"**Hint:** You will have to use an `if/else` conditional statement when calculating the fees."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 11 *(5 pts)*\n",
"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?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 12 *(10 pts)*\n",
"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.\n",
"\n",
"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?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "SageMath 7.3",
"language": "",
"name": "sagemath"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.10"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
`