authors are vetted experts in their fields and write on topics in which they have demonstrated experience. All of our content is peer reviewed and validated by Toptal experts in the same field.
米克罗斯卢卡奇
验证专家 在金融领域

Miklos是现金流建模和Python编程方面的专家, 曾在摩根士丹利和DBRS晨星工作. He is a Toptal finance expert and the director of the structured finance consulting company Pylink Ltd.

以前在

摩根士丹利(Morgan Stanley)
分享

Many financial experts are adept at using Excel to build financial models. 然而, 因为同行评议很困难, 版本控制, 不能形成递归函数, 对于更复杂的模型,Excel可能不是最佳选择. 尽管有这些缺点, many financial professionals still use Excel because they are less confident with programming languages such as Python.

Python是最容易学习的编程语言之一. 因为它在设计时就考虑了可读性和易用性, 它的代码简洁,接近于普通英语. 在本文中, I show how easy it is to build a Python cash flow model for loan payments by using the most basic functions, 包, 数据结构.

要继续学习,您将需要使用 Colaboratory (简称“Colab”), Google’s free web-based 笔记本 application that lets you write and execute code. Colab是一个Python解释器,它使用可以包含代码的单元格, 降低标记(对于容易设置样式的文本), 图片, 或者其他数据. Colab在您编写代码时持续存储代码的值, 当错误或漏洞出现时,使其快速而简单地被发现. (如果你还不想跳进去,就跟着这条 例子 Colab 笔记本.)

首先,确保你有你需要的工具

We will be building a model for an amortized loan that has a scheduled, periodic payment applied to both the loan’s principal and the interest. It has a fixed installment for each period and the interest portion of the payments decreases over time. 您将需要三个Python库, collections of software routines that prevent developers from having to write code from scratch, 对于这个模型- numpy, 熊猫, 和Matplotlib:

  • numpy-financial = = 1.0.0
  • 熊猫= = 1.2.3
  • matplotlib = = 3.2.2

在Colab, 默认安装了熊猫和Matplotlib包, 所以你只需要安装numpy-financial库, 你可以直接从Colab完成吗. 安装numpy-financial, 然后导入稍后需要的所有三个库, 从“文件”菜单中打开一个新的Colab笔记本, 并将以下代码粘贴到第一个代码单元格中:

# initial setup
!PIP安装numpy_financial
以pd方式导入熊猫
导入numpy_financial为NPF
进口matplotlib.Pyplot为PLT
从集合导入namedtuple

在我们进入下一步之前, let me explain the previous code and why it’s written the way it’s written. 尽管金融傻瓜的名字里有连字符, you must use an underscore in the name when you install and import it. (For more in格式ion and explanation on installing numpy_financial, check out the 文档.)你可能也会注意到缩写. Pre-defined aliases are commonly used for 包—NumPy is written as np, 熊猫 as pd. These aliases are used to save you from writing the full name of the package every time you would like to use it and also help to make your code more readable.

现在,使用NumPy来设置贷款特征

NumPy is one of the most popular Python libraries adding support for large, 多维数组, along with a significant collection of high-level mathematical functions to operate on those arrays. The numpy-financial library is a relatively new package made up of a collection of commonly used financial functions that have been separated from the main NumPy library and given their own pride of place.

The simplest way to calculate the scheduled interest and principal vectors for the life of our amortized loan is to use the PMT, IPMT, 和PPMT功能从numpy-financial包. The PMT function provides the fixed loan installment to pay the loan in full over a given number of periods. The IPMT and PPMT functions provide the interest and 本金支付s, respectively. 取决于周期的输入, the IPMT and PPMT functions can return values for a single period or a number of periods.

For this 例子, we will provide a range with the full life of the loan as the period input. 像这样, we will get vector arrays with the interest in 本金支付s for each period of the loan life:

#贷款特点
Original_balance = 500_000
券息= 0.08
期限= 120

#支付
周期= range(1, term+1)
利息支付= NPF.ipmt (
    Rate =息票/ 12,per=期间,nper=期限,pv=-original_balance)
Principal_payment = NPF.ppmt (
    Rate =息票/ 12,per=期间,nper=期限,pv=-original_balance)

You won’t “see” anything happen in your Colab file after entering the code—it is the basic loan in格式ion needed to do the rest of this exercise. (我用过的所有愚蠢的财务功能的列表, 他们的定义, 它们的输入, 可以在官方文件中找到吗.)

接下来,使用Matplotlib创建图表

虽然把向量作为输出是很好的, 最好以图表的形式将输出可视化, 特别是作为堆叠图. 为了建立图表,我们将使用 plt, the alias for the pyplot collection of functions from the matplotlib library. 在我们的例子中, we will add a legend in the top left corner and add titles to the x-axis and the y-axis. 由于我们不想要内部边框,我们将外边距设置为0.

添加另一个代码单元格,并插入以下代码:

plt.Stackplot(周期,利息支付,本金支付, 
              标签=[“兴趣”,“主要”])
plt.传奇(loc =“左上”)
plt.包含(“期限”)
plt.ylabel(“付款”)
plt.利润率(0,0)

正如我们所看到的,利息随着时间的推移而减少. The loan balance also decreases due to the 本金支付s in each period. To maintain the fixed installment, the principal portion has to increase.

最后,使用熊猫创建一个表

The 熊猫 package is the most commonly used Python package for manipulating numerical tables and time series. 它提供了快速的, 灵活的, and expressive data structures designed to make working with relational or labeled data both easy and intuitive. 我们将创建一个包含本金和利息支付的表, 以及每个期间的开始和结束贷款余额:

_#熊猫浮动格式_
pd.选项.显示.Float_格式 = '{:;.2f}'.格式

现金流量表
cf_data = {'Interest': interest_payment, 'Principal': principal_payment}
Cf_table = pd.DataFrame (data = cf_data指数=时间)
cf_table['Payment'] = cf_table['Interest'] + cf_table(主要的)
cf_table['Ending Balance'] = original_balance - \
                             cf_table(主要的).cumsum ()
cf_table[' initial Balance'] = [original_balance] + \
                                列表(cf_table[“期末余额”])(:1)
cf_table = cf_table[['期初余额','付款','利息', 
                     '本金','期末余额']]
cf_table.头(8)

应用第一行代码 显示格式规则 to make the table more readable by adding thousand separators and 显示ing the numbers to just two decimal places.

第二段代码指示Colab包含利息支付, 本金支付, 期末余额, 以及每个贷款期间的原始余额. The backslashes act as line breaks because we cannot have more than 79 characters in a single line.

Amounts surfaced in the chart have been shortened to two decimal places.

If you have been following along in your own Colab 笔记本, congratulations! You have now coded a simple scheduled amortization loan portfolio profile using Python.

你能做的还有很多 金融Python, including modeling for loans with variable interest coupons tied to a benchmark rate and other loan structures. Hopefully this loan model has given you a taste of how simple financial coding in Python can be.

了解基本知识

  • Python在金融中是如何使用的?

    Python can be used to pull data from spreadsheets and databases—and then to process that data using statistical tools. You can create and analyze everything from simple loan cash flow models to algorithmic trading strategies and more.

  • Python适合金融建模吗?

    Python是一种优秀的财务建模编程语言. 除了一个大型的标准工具库, 它提供了方便的访问金融特定, 第三方库,如NumPy和熊猫.

  • 学习金融学的Python需要多长时间?

    Python is one of the easiest coding languages to learn because it was designed with readability and ease of use in mind. 它的代码简洁,接近于普通英语. 你练习得越多,你学习Python的速度就越快. Some coders recommend working in Python for an hour a day as you’re learning.

聘请Toptal这方面的专家.
现在雇佣
米克罗斯卢卡奇

米克罗斯卢卡奇

验证专家 在金融领域

英国伦敦

2020年10月6日成为会员

作者简介

Miklos是现金流建模和Python编程方面的专家, 曾在摩根士丹利和DBRS晨星工作. He is a Toptal finance expert and the director of the structured finance consulting company Pylink Ltd.

authors are vetted experts in their fields and write on topics in which they have demonstrated experience. All of our content is peer reviewed and validated by Toptal experts in the same field.

以前在

摩根士丹利(Morgan Stanley)

世界级的文章,每周发一次.

输入您的电子邮件,即表示您同意我们的 隐私政策.

世界级的文章,每周发一次.

输入您的电子邮件,即表示您同意我们的 隐私政策.

金融专家

加入总冠军® 社区.