python - 从现金流列表中计算 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,而不是列表中所有三个的总和。如果你能帮助我非常感谢!
解决方案
您需要对函数中的各个现金流求和并返回。目前,您正在返回第一个现金流的 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.
永远记住,return
for循环中的语句将在第一次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)))
推荐阅读
- html - 如何将链接定位到右上角区域?(以标题为相对的绝对定位)
- reactjs - 如何在 React 中建模 1'000'000'000 个细胞?
- windows - 为什么这个汇编程序崩溃(重新组装的 ndisasm 输出)?
- data-science - 什么时候应该在数据处理中使用 Data Binning?
- python - 我使用子图模块绘制多个子图,但错误与'list'对象没有属性'set_xlim'
- node.js - Heroku 上带有 nodejs 的 Google 应用程序凭据:如何使用 dotenv 将 JSON 文件存储到 ENV 变量?
- reactjs - 为什么全局变量在 React 中执行两次
- argo-workflows - 使用 Argo Workflows 遍历 S3 文件夹中的所有文件
- c - 如何将 u_int32_t IPv4 地址分配给 C 中 sockaddr_in 的地址参数?(C 中的套接字编程)
- c++ - 将数据写入轮询无效套接字导致无法捕获的异常