-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloan_analyzer.py
241 lines (194 loc) · 9.77 KB
/
loan_analyzer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# coding: utf-8
import csv
from pathlib import Path
"""Part 1: Automate the Calculations.
Automate the calculations for the loan portfolio summaries.
First, let's start with some calculations on a list of prices for 5 loans.
1. Use the `len` function to calculate the total number of loans in the list.
2. Use the `sum` function to calculate the total of all loans in the list.
3. Using the sum of all loans and the total number of loans, calculate the average loan price.
4. Print all calculations with descriptive messages.
"""
loan_costs = [500, 600, 200, 1000, 450]
print("*** Part 1: Automate the Calculations ***")
# How many loans are in the list?
# @TODO: Use the `len` function to calculate the total number of loans in the list.
# Print the number of loans from the list
# YOUR CODE HERE!
print(f"There are {len(loan_costs)} loans in the list")
# What is the total of all loans?
# @TODO: Use the `sum` function to calculate the total of all loans in the list.
# Print the total value of the loans
# YOUR CODE HERE!
print(f"The total of all loans is: ${sum(loan_costs):.2f}")
# What is the average loan amount from the list?
# @TODO: Using the sum of all loans and the total number of loans, calculate the average loan price.
# Print the average loan amount
# YOUR CODE HERE!
average = sum(loan_costs) / len(loan_costs)
print(f"The average loan amount from the list is: ${average:.2f}")
print("")
"""Part 2: Analyze Loan Data.
Analyze the loan to determine the investment evaluation.
Using more detailed data on one of these loans, follow these steps to calculate a Present Value, or a "fair price" for what this loan would be worth.
1. Use get() on the dictionary of additional information to extract the **Future Value** and **Remaining Months** on the loan.
a. Save these values as variables called `future_value` and `remaining_months`.
b. Print each variable.
@NOTE:
**Future Value**: The amount of money the borrower has to pay back upon maturity of the loan (a.k.a. "Face Value")
**Remaining Months**: The remaining maturity (in months) before the loan needs to be fully repaid.
2. Use the formula for Present Value to calculate a "fair value" of the loan. Use a minimum required return of 20% as the discount rate.
3. Write a conditional statement (an if-else statement) to decide if the present value represents the loan's fair value.
a. If the present value of the loan is greater than or equal to the cost, then print a message that says the loan is worth at least the cost to buy it.
b. Else, the present value of the loan is less than the loan cost, then print a message that says that the loan is too expensive and not worth the price.
@NOTE:
If Present Value represents the loan's fair value (given the required minimum return of 20%), does it make sense to buy the loan at its current cost?
"""
# Given the following loan data, you will need to calculate the present value for the loan
loan = {
"loan_price": 500,
"remaining_months": 9,
"repayment_interval": "bullet",
"future_value": 1000,
}
print("*** Part 2: Analyze Loan Data ***")
# @TODO: Use get() on the dictionary of additional information to extract the Future Value and Remaining Months on the loan.
# Print each variable.
# YOUR CODE HERE!
future_value = loan.get("future_value")
remaining_months = loan.get("remaining_months")
print(f"The future value is: ${future_value:.2f}")
print(f"The remaining months are: {remaining_months} months.")
# @TODO: Use the formula for Present Value to calculate a "fair value" of the loan.
# Use a minimum required return of 20% as the discount rate.
# You'll want to use the **monthly** version of the present value formula.
# HINT: Present Value = Future Value / (1 + Discount_Rate/12) ** remaining_months
# YOUR CODE HERE!
discount_rate = 0.2 # Fixed discount rate of 20%
present_value = future_value / (1 + discount_rate / 12) ** remaining_months # Montly present value formula
print(f"With a discount rate of: {discount_rate*100:.2f}%, the present value is: ${present_value:.2f}")
# If Present Value represents what the loan is really worth, does it make sense to buy the loan at its cost?
# @TODO: Write a conditional statement (an if-else statement) to decide if the present value represents the loan's fair value.
# If the present value of the loan is greater than or equal to the cost, then print a message that says the loan is worth at least the cost to buy it.
# Else, the present value of the loan is less than the loan cost, then print a message that says that the loan is too expensive and not worth the price.
# YOUR CODE HERE!
print(f"Present value: ${present_value:.2f}")
print(f"Loan price: ${float(loan.get('loan_price')):.2f}")
if present_value >= loan.get("loan_price"):
print(f"The loan is worth at least the cost to buy it.")
else:
print(f"The loan is too expensive and not worth the price.")
print("")
"""Part 3: Perform Financial Calculations.
Perform financial calculations using functions.
1. Define a new function that will be used to calculate present value.
a. This function should include parameters for `future_value`, `remaining_months`, and the `annual_discount_rate`
b. The function should return the `present_value` for the loan.
2. Use the function to calculate the present value of the new loan given below.
a. Use an `annual_discount_rate` of 0.2 for this new loan calculation.
"""
# Given the following loan data, you will need to calculate the present value for the loan
new_loan = {
"loan_price": 800,
"remaining_months": 12,
"repayment_interval": "bullet",
"future_value": 1000,
}
print("*** Part 3: Perform Financial Calculations ***")
# @TODO: Define a new function that will be used to calculate present value.
# This function should include parameters for `future_value`, `remaining_months`, and the `annual_discount_rate`
# The function should return the `present_value` for the loan.
# YOUR CODE HERE!
def calculate_present_value(future_value, remaining_months, annual_discount_rate):
present_value = future_value / (1 + annual_discount_rate/12) ** remaining_months
return present_value
# @TODO: Use the function to calculate the present value of the new loan given below.
# Use an `annual_discount_rate` of 0.2 for this new loan calculation.
# YOUR CODE HERE!
# print(f"The present value of the loan is: ${present_value:.2f}")
remaining_months = new_loan["remaining_months"]
future_value = new_loan["future_value"]
annual_discount_rate = 0.2
print("New loan information")
print(f"Remaining months: {remaining_months}")
print(f"Future value: ${future_value:.2f}")
print(f"Annual discount rate: {(discount_rate*100):.2f}%")
new_present_value = calculate_present_value(float(future_value), float(remaining_months), float(annual_discount_rate))
print(f"The present value of the new loan is: ${new_present_value:.2f}")
print("")
"""Part 4: Conditionally filter lists of loans.
In this section, you will use a loop to iterate through a series of loans and select only the inexpensive loans.
1. Create a new, empty list called `inexpensive_loans`.
2. Use a for loop to select each loan from a list of loans.
a. Inside the for loop, write an if-statement to determine if the loan_price is less than or equal to 500
b. If the loan_price is less than or equal to 500 then append that loan to the `inexpensive_loans` list.
3. Print the list of inexpensive_loans.
"""
loans = [
{
"loan_price": 700,
"remaining_months": 9,
"repayment_interval": "monthly",
"future_value": 1000,
},
{
"loan_price": 500,
"remaining_months": 13,
"repayment_interval": "bullet",
"future_value": 1000,
},
{
"loan_price": 200,
"remaining_months": 16,
"repayment_interval": "bullet",
"future_value": 1000,
},
{
"loan_price": 900,
"remaining_months": 16,
"repayment_interval": "bullet",
"future_value": 1000,
},
]
print("*** Part 4: Conditionally filter lists of loans ***")
# @TODO: Create an empty list called `inexpensive_loans`
# YOUR CODE HERE!
inexpensive_loans = []
# @TODO: Loop through all the loans and append any that cost $500 or less to the `inexpensive_loans` list
# YOUR CODE HERE!
for loan in loans:
if loan["loan_price"] <= 500:
inexpensive_loans.append(loan)
# @TODO: Print the `inexpensive_loans` list
# YOUR CODE HERE!
print("Inexpensive loans:")
# print(inexpensive_loans)
for i in inexpensive_loans:
print(i)
print("")
"""Part 5: Save the results.
Output this list of inexpensive loans to a csv file
1. Use `with open` to open a new CSV file.
a. Create a `csvwriter` using the `csv` library.
b. Use the new csvwriter to write the header variable as the first row.
c. Use a for loop to iterate through each loan in `inexpensive_loans`.
i. Use the csvwriter to write the `loan.values()` to a row in the CSV file.
Hint: Refer to the official documentation for the csv library.
https://docs.python.org/3/library/csv.html#writer-objects
"""
# Set the output header
header = ["loan_price", "remaining_months", "repayment_interval", "future_value"]
# Set the output file path
output_path = Path("inexpensive_loans.csv")
print("*** Part 5: Save the results ***")
# @TODO: Use the csv library and `csv.writer` to write the header row
# and each row of `loan.values()` from the `inexpensive_loans` list.
# YOUR CODE HERE!
with open(output_path,'w', newline='') as csv_file:
csv_writer = csv.writer(csv_file) # Create a csv writer.
csv_writer.writerow(header) # Write the header row.
# Write a new row for each inexpensive loan.
for loan in inexpensive_loans:
csv_writer.writerow(loan.values())
print(f"The <{output_path}> file containing the inexpensive loans has been created.")
print("End of execution.")