首页 > 解决方案 > Python_计算期初和期末贷款余额

问题描述

我需要使用 Python(循环)计算贷款的期初余额和期末余额。我是 Python 新手,因此我在这方面遇到了一些困难。通过做一些谷歌搜索,我确实编写了以下代码:

 from __future__ import print_function
 import numpy as np

 amount = 20000
 int_rate = 0.012
 term = 5
 nper = 12
 mtly_pmt = 100

 fmt = 'year {0:2d} {1:8.2f} {2:8.2f}'

 for y in range(0, term + 1):
     print(fmt.format(
             y,
             np.fv(int_rate/nper, y*nper, mtly_pmt, -amount),
             np.fv(int_rate/nper, y*nper, mtly_pmt, -amount)
           )
     )

我的结果如下:

 year  0 20000.00 20000.00
 year  1 19034.70 19034.70
 year  2 18057.76 18057.76
 year  3 17069.02 17069.02
 year  4 16068.36 16068.36
 year  5 15055.62 15055.62

但是,它应该是这样的:

 Year      Opening       Closing
    0      20000         19034.70
    1      19034.70      18057.76
    2      18057.76      17069.02
    3      17069.20      16068.36
    4      16068.36      15055.62

如果您能帮助我得到这个结果,我将不胜感激。

标签: pythonpandasnumpy

解决方案


您只是打印了两次相同的值。这就是问题所在。相反,您必须保存之前的金额,然后使用它来计算下一个值。

from __future__ import print_function
import numpy as np

amount = 20000
int_rate = 0.012
term = 5
nper = 12
mtly_pmt = 100

fmt = '{0:4d} {1:10.2f} {2:10.2f}'
print("{:6} {:10} {:10}".format('Year','Opening','Closing'))

for y in range(0,term):    
    opening = amount
    closing = np.fv(int_rate/nper, nper, mtly_pmt, -amount)  
    amount = closing    
    print(fmt.format(y,opening,closing))

推荐阅读