首页 > 解决方案 > 从现金流列表中计算 NPV 的函数

问题描述

试图编写一个函数来计算现金流列表的现值。我知道 numpy 可以很容易地做到这一点,但对于一个任务,我必须为此编写自己的函数:/。

这是列表中的三个现金流以及贴现率。

cfList = [20, 50, 90]           
r = 0.05                        

这是我到目前为止编写的函数。f = 0 因为我想从第一个现金流开始(在本例中为 20)。i = 1,因为对于第一个流,它会上升到 1 次方,而第二个流 (50) 将是平方的,依此类推。

def npv(cfList, r):
    f = 0
    i = 1

    pv = cfList[f] / ((1 + r) ** i)

    while i < len(cfList):
        f += 1
        i += 1
        return pv


print(npv(cfList, r))

然而,这个输出只给了我第一个现金流的 PV,而不是列表中所有三个的总和。如果你能帮助我非常感谢!

标签: pythonpython-3.xfinance

解决方案


您需要对函数中的各个现金流求和并返回。目前,您正在返回第一个现金流的 pv 值,因为您的 for 循环中有一个 return 语句。

另外,我认为您检查 while 循环的方式i将意味着您将错过最后的付款值。通常您不需要自己实例化计数器变量(请参阅下面的示例):

def npv(cfList, r):
    f = 0
    i = 1

    pv = cfList[f] / ((1 + r) ** i)  # <-- this needs to be in the loop

    while i < len(cfList): # <-- i will break loop before last payment is calculated.
        f += 1
        i += 1
        return pv  # <-- this return here is the issue


print(npv(cfList, r))

NPV 是所有未来现金流的 PV 的总和,这是您需要计算的。例如:

def npv(cfList, r):

    sum_pv = 0  # <-- variable used to sum result

    for i, pmt in enumerate(cfList, start=1):  # <-- use of enumerate allows you to do away with the counter variables.
        sum_pv += pmt / ((1 + r) ** i)  # <-- add pv of one of the cash flows to the sum variable

    return sum_pv  # <-- only return the sum after your loop has completed.

永远记住,returnfor循环中的语句将在第一次return遇到时跳出循环。

另一种实现是从 PV 生成器产生单个 PV 并对结果求和:

def pv_gen(cfList, r):

    for i, pmt in enumerate(cfList, start=1):

        yield pmt / ((1 + r) ** i)

print(sum(pv_gen(cfList, r)))

推荐阅读