← All posts

By Mirza Ishraq, Founder · · Updated · 10 min read

NumPy Financial Functions: npv, irr and pmt in Python

Not financial advice or a suggestion. For educational purposes only.

The NumPy financial functions, including npv, irr and pmt, now live in a separate package: install numpy-financial and import it as npf. NumPy removed all ten in version 1.20. The current release, 1.1.0 from September 15, 2026, needs Python 3.13 or newer; on older Pythons, pip quietly installs the 2019 version 1.0.0 instead.

Every code block on this page was run on November 4, 2026 with Python 3.13.8, NumPy 2.5.4, numpy-financial 1.1.0 and SciPy 1.18.1, in the order shown. Each output is pasted from that run.

Key takeaways

  • np.npv, np.irr and np.pmt are gone from NumPy 1.20 and later. pip install numpy-financial, then import numpy_financial as npf.
  • Version 1.1.0 needs Python 3.13. On Python 3.12, pip installs 1.0.0, where npv takes only one rate and irr has no raise_exceptions.
  • npf.npv treats the first cash flow as today. Excel’s NPV discounts it one period, so the same six numbers give 517,892.29 in Python and 479,529.89 in Excel. Keep the first value outside Excel’s NPV and they match.
  • When cash flows change sign more than once, irr returns one of several answers. When they never change sign, it returns nan.
  • There is no XIRR. Two short functions with SciPy reproduce Microsoft’s own XIRR example.

Where did NumPy’s financial functions go?

NumPy deprecated its financial functions in version 1.18 and removed them in 1.20, following NEP 32, a 2019 proposal by Warren Weckesser. The NumPy 1.20 release notes list the ten that went, and point to the numpy-financial package that replaced them.

One of the proposal’s reasons matters when you use them: the functions “do not handle real dates and calendars.” Every one of them assumes evenly spaced periods.

Function Returns The question it answers
fv Future value What will saving 500 a month grow to?
pv Present value What is 100,000 in ten years worth today?
pmt Payment per period What is the monthly payment on a loan?
ipmt Interest part of one payment How much of payment 1 is interest?
ppmt Principal part of one payment How much of payment 1 repays the loan?
nper Number of periods How many months to clear a balance?
rate Rate per period What yearly rate doubles money in 10 years?
npv Net present value Is a project worth its cost at 8%?
irr Internal rate of return At what rate does the NPV reach zero?
mirr Modified IRR IRR with a stated borrowing and reinvestment rate

Install numpy-financial and check the version

Run pip install numpy-financial, then import it as npf, the alias its docs recommend. The package is free and open source under the BSD 3-clause license. Check the version first, because the one you get depends on your Python. If pip and import are new to you, the Python for finance courses and books list gives each one’s prerequisites in the provider’s own words.

import numpy_financial as npf
print(npf.__version__)
1.1.0

Version 1.1.0, released on GitHub on September 15, 2026, is the first new release since 1.0.0 in October 2019. PyPI lists it as requiring Python 3.13 or newer, so on Python 3.12 pip installs 1.0.0 without a warning. The difference shows up below: in 1.0.0, a list of rates passed to npv raises a TypeError, and irr rejects raise_exceptions.

One sign convention runs through every function: money you pay out is negative, money you receive is positive.

Loan payments with pmt, ipmt and ppmt

npf.pmt returns the fixed payment per period that repays a loan, and ipmt and ppmt split one payment into its interest and principal. It takes the rate per period, the number of periods and the amount borrowed. The example is a 400,000 loan at an assumed 6.5% a year, repaid monthly over 30 years.

rate = 0.065 / 12   # 6.5% a year, paid monthly
n = 30 * 12         # 360 monthly payments
loan = 400_000

payment = npf.pmt(rate, n, loan)
first_interest = npf.ipmt(rate, 1, n, loan)
first_principal = npf.ppmt(rate, 1, n, loan)
print(f"Monthly payment:   {payment:,.2f}")
print(f"  interest part:   {first_interest:,.2f}")
print(f"  principal part:  {first_principal:,.2f}")
print(f"Total interest:    {-payment * n - loan:,.2f}")
Monthly payment:   -2,528.27
  interest part:   -2,166.67
  principal part:  -361.61
Total interest:    510,177.95

The payment is negative because it leaves your account. Of the first 2,528.27, 2,166.67 is interest and 361.61 repays the loan. Over 360 payments the interest comes to 510,177.95, more than the loan itself.

Future value, present value, nper and rate

fv, pv, pmt, nper and rate all solve one equation, which ties together a present value, a payment per period, a number of periods, a rate per period and a future value. Give any four and each function returns the fifth; the equation is in each function’s docstring.

# Save 500 a month for 30 years at an assumed 7% a year
print(f"fv:   {npf.fv(0.07 / 12, 30 * 12, -500, 0):,.2f}")

# What is 100,000 received in 10 years worth today at 5%?
print(f"pv:   {npf.pv(0.05, 10, 0, 100_000):,.2f}")

# Months to clear a 10,000 card balance at 24% APR, paying 300 a month
print(f"nper: {npf.nper(0.24 / 12, -300, 10_000):.1f}")

# The yearly rate that turns 1,000 into 2,000 in 10 years
print(f"rate: {npf.rate(10, 0, -1_000, 2_000):.4%}")
fv:   609,985.50
pv:   -61,391.33
nper: 55.5
rate: 7.1773%

At an assumed 7%, 500 a month grows to 609,985.50 in 30 years. 100,000 due in 10 years is worth 61,391.33 today at 5%, shown negative because that is what you would pay for it. The card balance takes 55.5 months to clear. Doubling money in 10 years takes 7.1773% a year, close to the rule of 72’s 7.2%.

How to calculate NPV and IRR in Python

NPV, net present value, discounts each cash flow back to today at a chosen rate and adds them up. For a project with one outlay followed by inflows, a positive NPV means it earns more than that rate. IRR, the internal rate of return, is the rate at which the NPV is exactly zero. npf.npv(rate, values) and npf.irr(values) compute them.

The example uses the cash flows the numpy-financial docs use for irr: 250,000 out today, then five yearly inflows. The docs show an IRR of 0.5672303344358536, so you can check your install against it.

project = [-250_000, 100_000, 150_000, 200_000, 250_000, 300_000]

print(f"NPV at 8%: {npf.npv(0.08, project):,.2f}")
print(f"IRR:       {npf.irr(project):.6f}")
NPV at 8%: 517,892.29
IRR:       0.567230

At an 8% discount rate the NPV is 517,892.29. The IRR, 56.7%, is the discount rate at which the NPV falls to zero.

Why doesn’t npf.npv match Excel’s NPV?

npf.npv treats the first value as happening today, undiscounted. Excel’s NPV function treats every value as arriving at the end of a period, so the first one is discounted too. Microsoft’s help says a cash flow at the start of the first period “must be added to the NPV result”, outside the function.

def excel_npv(rate, values):
    """Excel's NPV: every value sits at the END of its period, so the first is discounted too."""
    return sum(v / (1 + rate) ** (i + 1) for i, v in enumerate(values))

print(f"npf.npv(8%, all six):        {npf.npv(0.08, project):,.2f}")
print(f"Excel =NPV(8%, B1:B6):       {excel_npv(0.08, project):,.2f}")
print(f"Excel =NPV(8%, B2:B6) + B1:  {excel_npv(0.08, project[1:]) + project[0]:,.2f}")
print(f"Gap:                         {npf.npv(0.08, project) - excel_npv(0.08, project):,.2f}")
npf.npv(8%, all six):        517,892.29
Excel =NPV(8%, B1:B6):       479,529.89
Excel =NPV(8%, B2:B6) + B1:  517,892.29
Gap:                         38,362.39

With all six values inside Excel’s NPV, every cash flow is discounted one extra year and the result is 38,362.39 lower. With the outlay outside, =NPV(8%, B2:B6) + B1, Excel and npf.npv agree to the cent. If you’re checking a spreadsheet someone else built, look at where the first cell sits.

An NPV profile: npv at many rates at once

In 1.1.0, npv accepts an array of rates and returns one NPV for each, so a whole NPV profile is one call. In 1.0.0 the same line raises a TypeError.

import numpy as np
import matplotlib.pyplot as plt

rates = np.linspace(0, 0.80, 81)
profile = npf.npv(rates, project)   # one call, 81 rates (new in 1.1.0)
irr = npf.irr(project)

fig, ax = plt.subplots()
ax.plot(rates * 100, profile / 1000)
ax.axhline(0, color="#808080", linewidth=0.8)
ax.plot([irr * 100], [0], "o", markersize=7)
ax.annotate(f"IRR {irr:.1%}", (irr * 100, 0), xytext=(8, 12), textcoords="offset points")
ax.set_title("NPV of the project at discount rates from 0% to 80%")
ax.set_xlabel("Discount rate (%)")
ax.set_ylabel("NPV (thousands)")
fig.savefig("npv-profile.png")
print(f"NPV at 0%: {profile[0]:,.0f}   at 80%: {profile[-1]:,.0f}")
NPV at 0%: 750,000   at 80%: -74,163

Line chart of the example project’s NPV falling from 750,000 at a 0% discount rate to below zero past 56.7%, with the IRR marked where the line crosses zero Chart made by this post’s code from the example cash flows above. Not investment advice.

At 0% the NPV is simply the sum of the cash flows, 750,000. The line crosses zero at the IRR and is at -74,163 by 80%.

When irr returns nan or only one of two answers

IRR is the root of a polynomial, and when the cash flows change sign more than once there can be more than one root. The flows -100, 230, -132 have two: at 10% and at 20%, the NPV is zero.

flows = [-100, 230, -132]          # the sign changes twice
print("irr:              ", round(npf.irr(flows), 6))
print("NPV at 10% and 20%:", npf.npv([0.10, 0.20], flows).round(6) + 0)
print("largest root:     ", round(npf.irr(flows, selection_logic=np.max), 6))
print("mirr at 10%/10%:  ", round(npf.mirr(flows, 0.10, 0.10), 6))

print("all positive:     ", npf.irr([100, 100]))
try:
    npf.irr([100, 100], raise_exceptions=True)
except Exception as e:
    print(type(e).__name__, "-", e)
irr:               0.1
NPV at 10% and 20%: [0. 0.]
largest root:      0.2
mirr at 10%/10%:   0.1
all positive:      nan
NoRealSolutionError - No real solution exists for IRR since all cashflows are of the same sign.

By default irr returned 10%. selection_logic=np.max picks the other root. Neither is wrong, and that is the trouble with IRR on flows like these. MIRR gives one answer by asking for the rate you borrow at and the rate you reinvest at; with 10% for both, it returns 10%.

When every cash flow has the same sign there is no IRR. irr returns nan by default, and with raise_exceptions=True it raises npf.NoRealSolutionError. The 1.1.0 docstring calls it NoRealSolutionException, but the class is named NoRealSolutionError, so catch that name.

How to calculate XIRR in Python for irregular dates

numpy-financial has no XIRR. Excel’s XIRR discounts each payment by its actual date, on a 365-day year. That fits in two short functions with SciPy’s brentq root finder:

from datetime import date
from scipy.optimize import brentq

def xnpv(rate, cashflows, dates):
    t0 = dates[0]
    return sum(cf / (1 + rate) ** ((d - t0).days / 365) for cf, d in zip(cashflows, dates))

def xirr(cashflows, dates):
    return brentq(lambda r: xnpv(r, cashflows, dates), -0.99, 10)

# Microsoft's XIRR example
flows = [-10_000, 2_750, 4_250, 3_250, 2_750]
when = [date(2008, 1, 1), date(2008, 3, 1), date(2008, 10, 30), date(2009, 2, 15), date(2009, 4, 1)]
print(f"{xirr(flows, when):.6f}  ({xirr(flows, when):.2%})")
0.373363  (37.34%)

These are the values and dates from Microsoft’s help page, which gives 0.373362535 (37.34%); the two agree to six decimal places. brentq needs the NPV to change sign between its two bounds, here -99% and 1,000%, and raises a ValueError if it doesn’t.

FAQ

Why does np.npv give an AttributeError?

NumPy 1.20 removed it. On NumPy 2.5.4 the error is a plain AttributeError: module 'numpy' has no attribute 'npv', with no hint about where it went. The same goes for np.irr, np.pmt and the other seven: they are in numpy-financial.

Does numpy-financial have XIRR or XNPV?

No. Version 1.1.0 has the ten functions in the table above, all for evenly spaced periods. The xnpv and xirr functions in this post fill the gap.

What is the difference between irr and mirr?

irr finds the rate at which the NPV is zero, and when the cash flows change sign more than once it can have several answers. mirr takes two more inputs, the rate you borrow at and the rate you reinvest at, and returns one answer. On the flows -100, 230, -132, irr can return 10% or 20%; mirr with 10% for both returns 10%.

Is numpy-financial still maintained?

Yes. Version 1.1.0 came out on September 15, 2026, almost seven years after 1.0.0. Its release notes list a new irr solver, npv, nper and mirr that work on arrays, and inline type hints.

Where to go next

These functions are the arithmetic inside a discounted cash flow model: financial modeling with Python builds one from SEC filings with npf.npv. For returns, volatility and risk on market prices, see quantitative finance in Python, and the Python for finance guide maps the rest.