作者都是各自领域经过审查的专家,并撰写他们有经验的主题. 我们所有的内容都经过同行评审,并由同一领域的Toptal专家验证.
米克罗斯卢卡奇
验证专家 在金融领域

Miklos is an expert in cash flow modeling and Python programming, and has worked for 摩根士丹利(Morgan Stanley) and DBRS Morningstar. 他是Toptal金融专家和结构金融咨询公司Pylink Ltd的董事.

以前在

摩根士丹利(Morgan Stanley)
分享

许多金融专家都擅长使用Excel建立金融模型. 然而, because of difficulties with peer review, 版本控制, and the inability to form recursive functions, Excel may not be the best choice for more sophisticated models. 尽管有这些缺点, 许多金融专业人士仍在使用Excel,因为他们对Python等编程语言缺乏信心.

Python is one of the easiest programming languages to learn. Because it was designed with readability and ease of use in mind, its code is concise and close to plain English. 在本文中, 我将展示使用最基本的函数为贷款支付构建Python现金流模型是多么容易, 包, 数据结构.

To follow along, you will need to use Colaboratory (简称“Colab”), 谷歌的一款免费的基于网络的笔记本程序,可以让你编写和执行代码. Colab is a Python interpreter that uses cells that can contain code, Markdown (for easily styled text), 图片, 或者其他数据. Colab continuously stores the values of your code as you write, making it quick and simple to catch mistakes or bugs as they appear. (If you don’t want to jump in just yet, follow along with this 例子 Colab 笔记本.)

First, Make Sure You Have the 工具 You Need

我们将为一个有一个计划的摊销贷款建立一个模型, 贷款本金和利息的定期支付. 它在每个时期有固定的分期付款,支付的利息部分随着时间的推移而减少. You will need three Python libraries, 防止开发人员从头编写代码的软件例程集合, 对于这个模型- numpy, 熊猫, 和Matplotlib:

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

在Colab, the 熊猫 and Matplotlib 包 are installed by default, so you only need to install the numpy-financial library, which you can do directly from Colab. 安装numpy-financial, and import all three libraries you will need later, open a new Colab 笔记本 from the File menu, and paste the following into the first code cell:

# initial setup
!pip install numpy_financial
以pd方式导入熊猫
import numpy_financial as npf
进口matplotlib.Pyplot为PLT
from collections import namedtuple

Before we move on to the next step, 让我解释一下前面的代码,以及为什么它是这样写的. Even though numpy-financial’s name contains a hyphen, 在安装和导入它时,必须在名称中使用下划线. (有关安装numpy_financial的更多信息和说明,请查看 文档.) You may notice abbreviations, too. 预定义的别名通常用于包—numpy写成np, 熊猫写成pd. 使用这些别名可以避免每次使用包时都要编写包的全名,还可以帮助提高代码的可读性.

Now, Use NumPy to Set Up the Loan Characteristics

NumPy是最流行的Python库之一,它增加了对large, 多维数组, 以及一组重要的高级数学函数来操作这些数组. NumPy -financial库是一个相对较新的包,由一组常用的金融功能组成,这些功能已经从主NumPy库中分离出来,并被赋予了自己的骄傲地位.

计算分期偿还贷款期限内的计划利息和本金向量的最简单方法是使用PMT, IPMT, and PPMT functions from the numpy-financial package. PMT函数提供固定贷款分期付款,以便在给定的期间内全额支付贷款. IPMT和PPMT函数分别提供利息和本金支付. Depending on the input to the period, IPMT和PPMT函数可以返回单个周期或多个周期的值.

对于本例,我们将提供一个范围,其贷款的整个生命周期作为期间输入. 像这样, 我们将得到一个向量数组,其中包含每个贷款周期的本金支付利息:

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

#支付
周期= range(1, term+1)
利息支付= NPF.ipmt (
    rate=coupon / 12, per=periods, nper=term, pv=-original_balance)
Principal_payment = NPF.ppmt (
    rate=coupon / 12, per=periods, nper=term, pv=-original_balance)

在输入代码之后,您不会在Colab文件中“看到”任何事情发生——这是完成本练习其余部分所需的基本贷款信息. (A list of all the numpy-financial functions I’ve used, 他们的定义, 它们的输入, can be found in the official 文档.)

Next, Use Matplotlib to Create a Chart

While it is good to have the vectors as an output, it may be best to visualize the output in the form of a chart, specifically as a stack plot. To set up the chart, we will use plt,是matplotlib库中函数pyplot集合的别名. 在我们的例子中, 我们将在左上角添加一个图例,并在x轴和y轴上添加标题. As we do not want an internal border, we set the margins to 0.

Add another code cell, and insert the following code:

plt.stackplot(periods, interest_payment, principal_payment, 
              labels=['Interest', 'Principal'])
plt.传奇(loc =“左上”)
plt.包含(“期限”)
plt.ylabel(“付款”)
plt.利润率(0,0)

As we can see, the interest decreases over time. 由于每个时期的本金支付,贷款余额也会减少. 为了保持固定的分期付款,本金必须增加.

Finally, Use 熊猫 to Create a Table

熊猫包是最常用的Python包,用于操作数字表和时间序列. 它提供了快速的, 灵活的, 表达性数据结构的设计使处理关系数据或标记数据既简单又直观. We will create a table that includes principal and interest payments, as well as starting and ending loan balances for each period:

_# pandas float 格式ting_
pd.选项.显示.Float_格式 = '{:;.2f}'.格式

现金流量表
cf_data ={'利息':利息支付,'本金':本金支付}
Cf_table = pd.DataFrame(data=cf_data, index=periods)
cf_table['Payment'] = cf_table['Interest'] + cf_table(主要的)
cf_table['Ending Balance'] = original_balance - \
                             cf_table(主要的).cumsum ()
cf_table['Beginning Balance'] = [original_balance] + \
                                list(cf_table['Ending Balance'])[:-1]
cf_table = cf_table[['Beginning Balance', 'Payment', 'Interest', 
                     'Principal', 'Ending Balance']]
cf_table.头(8)

The first line of code applies 显示格式规则 通过添加千位分隔符并将数字显示到小数点后两位,使表更具可读性.

The second chunk of code instructs Colab to include interest payment, 本金支付, 期末余额, and original balance for each loan period. 反斜杠充当换行符,因为一行中不能有超过79个字符.

图表上的金额已缩短到小数点后两位.

如果你一直在用你自己的Colab笔记本跟随我,恭喜你! 现在,您已经使用Python编写了一个简单的计划分期偿还贷款组合配置文件.

There is much more you can do with 金融Python, 包括与基准利率和其他贷款结构挂钩的可变息票的贷款建模. 希望这个贷款模型已经让您体验到Python中的财务编码是多么简单.

了解基本知识

  • How is Python used in finance?

    Python可用于从电子表格和数据库中提取数据,然后使用统计工具处理这些数据. 您可以创建和分析从简单的贷款现金流模型到算法交易策略等所有内容.

  • Is Python good for financial modeling?

    Python is an excellent programming language for financial modeling. In addition to a large standard library of tools, it offers easy access to finance-specific, third-party libraries such as NumPy and 熊猫.

  • How long does it take to learn 金融Python?

    Python是最容易学习的编程语言之一,因为它在设计时就考虑了可读性和易用性. Its code is concise and close to plain English. The more you practice, the quicker you will learn Python. 一些程序员建议你在学习Python的过程中每天花一个小时学习.

Hire a Toptal expert on this topic.
现在雇佣
米克罗斯卢卡奇

米克罗斯卢卡奇

验证专家 在金融领域

英国伦敦

Member since October 6, 2020

作者简介

Miklos is an expert in cash flow modeling and Python programming, and has worked for 摩根士丹利(Morgan Stanley) and DBRS Morningstar. 他是Toptal金融专家和结构金融咨询公司Pylink Ltd的董事.

作者都是各自领域经过审查的专家,并撰写他们有经验的主题. 我们所有的内容都经过同行评审,并由同一领域的Toptal专家验证.

以前在

摩根士丹利(Morgan Stanley)

World-class articles, delivered weekly.

Subscription implies consent to our 隐私政策

World-class articles, delivered weekly.

Subscription implies consent to our 隐私政策

金融专家

加入总冠军® 社区.