เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

จำลองการชำระเงินรายงวด (II)

ต่อยอดโปรแกรมจากแบบฝึกหัดที่แล้ว โดยเพิ่มการเก็บข้อมูลเงินต้นและดอกเบี้ยที่ชำระในแต่ละงวด แล้วแสดงผลในรูปแบบกราฟแทนการพิมพ์ค่าออกมา

โค้ดสำหรับการพล็อตกราฟเตรียมไว้ให้แล้ว สิ่งที่ต้องทำคือเขียน logic ภายใน for loop และกำหนดค่าเริ่มต้นของตัวแปรที่จะถูกอัปเดตในแต่ละรอบ

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Python เบื้องต้นสำหรับแนวคิดทางการเงิน

ดูคอร์ส

คำแนะนำการฝึกหัด

  • เก็บค่า interest_paid และ principal_paid สำหรับแต่ละงวด
  • คำนวณ principal_remaining ของแต่ละงวด โดยอิงจากจำนวนเงินต้นที่ชำระและเงินต้นคงเหลือ
  • รันโค้ดที่เตรียมไว้เพื่อพล็อตกราฟแสดงการชำระดอกเบี้ยและเงินต้นรายเดือน

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# 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()
แก้ไขและรันโค้ด