Mô phỏng các khoản thanh toán định kỳ (II)
Bạn quyết định mở rộng chương trình từ bài trước để lưu lại phần tiền gốc và tiền lãi đã trả ở mỗi kỳ, và vẽ biểu đồ kết quả thay vì chỉ in ra.
Trong ví dụ này, mã vẽ biểu đồ đã được chuẩn bị sẵn, nên bạn chỉ cần hoàn thiện phần logic bên trong vòng lặp for và khởi tạo các biến sẽ được cập nhật ở mỗi lần lặp.
Bài tập này là một phần của khóa học
Nhập môn các khái niệm tài chính với Python
Hướng dẫn bài tập
- Lưu lại
interest_paidvàprincipal_paidcho mỗi kỳ. - Tính
principal_remainingcho mỗi kỳ dựa trên khoản trả gốc và số dư gốc còn lại. - Chạy mã đã cung cấp để vẽ biểu đồ so sánh tiền lãi và tiền gốc hàng tháng.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
# Loop through each mortgage payment period
for i in range(0, mortgage_payment_periods):
# Handle the case for the first iteration
if i == 0:
previous_principal_remaining = mortgage_loan
else:
previous_principal_remaining = principal_remaining[i-1]
# Calculate the interest based on the previous principal
interest_payment = round(previous_principal_remaining*mortgage_rate_periodic, 2)
principal_payment = round(periodic_mortgage_payment - interest_payment, 2)
# Catch the case where all principal is paid off in the final period
if previous_principal_remaining - principal_payment < 0:
principal_payment = previous_principal_remaining
# Collect the historical values
interest_paid[i] = ____
principal_paid[i] = ____
principal_remaining[i] = ____
# Plot the interest vs principal
plt.plot(interest_paid, color="red")
plt.plot(principal_paid, color="blue")
plt.legend(handles=[interest_plot, principal_plot], loc=2)
plt.show()