Ejemplo n.º 1
0
 def calcPrice(self):
     if self.par != None and self.cr != None and self.cy != None:
         self.pr = (self.par*self.cr)/self.cy
     elif self.par != None and self.cr != None and self.ytm != None:
         self.pr = -1*np.pv(0.5*self.ytm, 2.0*self.mat, 0.5*self.par*self.cr, self.par)
         
     print "Bond price = $%.2f" % self.pr
Ejemplo n.º 2
0
    def calculate_bond_price(self):
        present_value = np.pv(
            rate=self.annual_required_return / self.annual_payment_frequency,
            nper=self.term_to_maturity * self.annual_payment_frequency,
            pmt=self.semi_annual_coupon_payment,
            fv=self.face_value
        )

        return -0.1 * present_value
Ejemplo n.º 3
0
 def _calc(self):
     # shortcut if the portfolio is 0...some of the math
     # below doesn't like 0s.
     if self.portfolio.value == 0:
         return Decimal(0)
     amount = pmt(self.rate, self.final_age - self.current_age, self.portfolio.value)
     desired_pmt = self.desired_payment * self.cumulative_inflation
     desired_value = pv(float(self.rate), self.final_age - self.current_age, float(-desired_pmt), when='begin')
     desired_value = Decimal(desired_value)
     tilt = (self.portfolio.value / desired_value) ** self.tilt
     return amount * tilt
Ejemplo n.º 4
0
def getFitForN(N):
    a = []
    for i in range(1, N + 1):
        row = []
        for j in range(N - 1, -1, -1):
            row.append(pow(i, j))
        a.append(row)
    a = na(a)
    b = na([sequence(i) for i in range(1, N + 1)])
    coeffs = solve(a, b)
    fit = pv(coeffs, N + 1)
    return fit
 def levelize_costs(self):
     if hasattr(self, 'is_levelized'):
         inflation = float(cfg.cfgfile.get('case', 'inflation_rate'))
         rate = self.cost_of_capital - inflation
         if self.is_levelized == 0:
             self.values_level = - np.pmt(rate, self.book_life, 1, 0, 'end') * self.values
             util.convert_age(self, vintages=self.vintages, years=self.years, attr_from='values_level', attr_to='values_level', reverse=False)
         else:
             self.values_level = self.values.copy()
             util.convert_age(self, vintages=self.vintages, years=self.years, attr_from='values_level', attr_to='values_level', reverse=False)
             self.values = np.pv(rate, self.book_life, -1, 0, 'end') * self.values
     else:
         util.convert_age(self, vintages=self.vintages, years=self.years, reverse=False)
 def levelize_costs(self):
     if hasattr(self, 'is_levelized'):
         inflation = float(cfg.cfgfile.get('case', 'inflation_rate'))
         rate = self.cost_of_capital - inflation
         if self.is_levelized == 0:
             self.values_level = - np.pmt(rate, self.book_life, 1, 0, 'end') * self.values
             util.convert_age(self, vintages=self.vintages, years=self.years, attr_from='values_level', attr_to='values_level', reverse=False)
         else:
             self.values_level = self.values.copy()
             util.convert_age(self, vintages=self.vintages, years=self.years, attr_from='values_level', attr_to='values_level', reverse=False)
             self.values = np.pv(rate, self.book_life, -1, 0, 'end') * self.values
     else:
         raise ValueError('Supply Technology id %s needs to indicate whether costs are levelized ' %self.id)
Ejemplo n.º 7
0
def calc_compounding ( _rate, _periods, _principal, _contribution, _delta, _inflation ) :
	in_rate = 0.01 * _rate
	in_delta   = 0.01 * _delta
	in_contrib = -1* _contribution
	in_princ   = -1* _principal
	in_inflation = 0.01* inflation
	print("rate %g, periods %g, principal %g, contribution %g, delta %g, inflation %g" %( _rate, _periods, in_princ, in_contrib, _delta, _inflation))
	cf1 = np.array([round(np.fv(in_rate, i, in_contrib, in_princ, when='end'),2) for i in range(1,periods+1)])
	cf2 = np.array([round(np.fv((in_rate-in_delta), i, in_contrib, in_princ, when='end'),2) for i in range(1,periods+1)])
	if _inflation == 0:
		return(np.subtract(cf1,cf2))
	else:
		diff = np.subtract(cf1,cf2)
		return np.array([round(np.pv(in_inflation, i, 0, (-1*diff[i])),2)  for i in range(_periods)])
Ejemplo n.º 8
0
    def harvest(self):
        amount = yield
        while True:
            # In order to get rid of the memory effect, the parameters to PV
            # have to independent of *when* you retire. But they can use current information

            # This is just our life expectancy.
            nper = max(5, 100 - self.current_age)
            #nper = mortality.life_expectancy(self.current_age, None)

            # But let's also subtract out however many years worth of bonds
            # we currently have. This assumes that bonds keep up with inflation
            # which is a dubious proposition...
            #nper -= int(self.portfolio.bonds / amount)

            # Set a minimum years worth of stock. Pretty arbitrarily chosen...
            portfolio_goal = Decimal(-numpy.pv(float(self.rate), nper, float(amount), when='beginning'))

            if self.portfolio.stocks >= portfolio_goal:
                #import pdb;pdb.set_trace()
                #harvest_amount = self.portfolio.stocks - portfolio_goal
                harvest_amount = self.portfolio.stocks / 4
                self.portfolio.sell_stocks(harvest_amount)
                self.portfolio.buy_bonds(harvest_amount)
                #print(self.current_age, " ", harvest_amount.to_integral_value(), " ", self.portfolio.stocks.to_integral_value(), "{%d}" % amount)
            else:
                #print(self.current_age, "[", portfolio_goal.to_integral_value(), "]", self.portfolio.stocks.to_integral_value(), "{%d}" % amount)
                pass

            amount = min(amount, self.portfolio.value)

            amount_bonds = min(amount, self.portfolio.bonds)
            amount_stocks = amount - amount_bonds
            self.portfolio.sell_bonds(amount_bonds)
            self.portfolio.sell_stocks(amount_stocks)
            
            amount = yield self.portfolio.empty_cash()

            self.current_age += 1
Ejemplo n.º 9
0
    def test_when(self):
        # begin
        assert_almost_equal(np.rate(10, 20, -3500, 10000, 1), np.rate(10, 20, -3500, 10000, "begin"), 4)
        # end
        assert_almost_equal(np.rate(10, 20, -3500, 10000), np.rate(10, 20, -3500, 10000, "end"), 4)
        assert_almost_equal(np.rate(10, 20, -3500, 10000, 0), np.rate(10, 20, -3500, 10000, "end"), 4)

        # begin
        assert_almost_equal(np.pv(0.07, 20, 12000, 0, 1), np.pv(0.07, 20, 12000, 0, "begin"), 2)
        # end
        assert_almost_equal(np.pv(0.07, 20, 12000, 0), np.pv(0.07, 20, 12000, 0, "end"), 2)
        assert_almost_equal(np.pv(0.07, 20, 12000, 0, 0), np.pv(0.07, 20, 12000, 0, "end"), 2)

        # begin
        assert_almost_equal(np.fv(0.075, 20, -2000, 0, 1), np.fv(0.075, 20, -2000, 0, "begin"), 4)
        # end
        assert_almost_equal(np.fv(0.075, 20, -2000, 0), np.fv(0.075, 20, -2000, 0, "end"), 4)
        assert_almost_equal(np.fv(0.075, 20, -2000, 0, 0), np.fv(0.075, 20, -2000, 0, "end"), 4)

        # begin
        assert_almost_equal(np.pmt(0.08 / 12, 5 * 12, 15000.0, 0, 1), np.pmt(0.08 / 12, 5 * 12, 15000.0, 0, "begin"), 4)
        # end
        assert_almost_equal(np.pmt(0.08 / 12, 5 * 12, 15000.0, 0), np.pmt(0.08 / 12, 5 * 12, 15000.0, 0, "end"), 4)
        assert_almost_equal(np.pmt(0.08 / 12, 5 * 12, 15000.0, 0, 0), np.pmt(0.08 / 12, 5 * 12, 15000.0, 0, "end"), 4)

        # begin
        assert_almost_equal(np.ppmt(0.1 / 12, 1, 60, 55000, 0, 1), np.ppmt(0.1 / 12, 1, 60, 55000, 0, "begin"), 4)
        # end
        assert_almost_equal(np.ppmt(0.1 / 12, 1, 60, 55000, 0), np.ppmt(0.1 / 12, 1, 60, 55000, 0, "end"), 4)
        assert_almost_equal(np.ppmt(0.1 / 12, 1, 60, 55000, 0, 0), np.ppmt(0.1 / 12, 1, 60, 55000, 0, "end"), 4)

        # begin
        assert_almost_equal(np.ipmt(0.1 / 12, 1, 24, 2000, 0, 1), np.ipmt(0.1 / 12, 1, 24, 2000, 0, "begin"), 4)
        # end
        assert_almost_equal(np.ipmt(0.1 / 12, 1, 24, 2000, 0), np.ipmt(0.1 / 12, 1, 24, 2000, 0, "end"), 4)
        assert_almost_equal(np.ipmt(0.1 / 12, 1, 24, 2000, 0, 0), np.ipmt(0.1 / 12, 1, 24, 2000, 0, "end"), 4)

        # begin
        assert_almost_equal(np.nper(0.075, -2000, 0, 100000.0, 1), np.nper(0.075, -2000, 0, 100000.0, "begin"), 4)
        # end
        assert_almost_equal(np.nper(0.075, -2000, 0, 100000.0), np.nper(0.075, -2000, 0, 100000.0, "end"), 4)
        assert_almost_equal(np.nper(0.075, -2000, 0, 100000.0, 0), np.nper(0.075, -2000, 0, 100000.0, "end"), 4)
Ejemplo n.º 10
0
    def test_when(self):
        # begin
        assert_equal(np.rate(10, 20, -3500, 10000, 1),
                     np.rate(10, 20, -3500, 10000, 'begin'))
        # end
        assert_equal(np.rate(10, 20, -3500, 10000),
                     np.rate(10, 20, -3500, 10000, 'end'))
        assert_equal(np.rate(10, 20, -3500, 10000, 0),
                     np.rate(10, 20, -3500, 10000, 'end'))

        # begin
        assert_equal(np.pv(0.07, 20, 12000, 0, 1),
                     np.pv(0.07, 20, 12000, 0, 'begin'))
        # end
        assert_equal(np.pv(0.07, 20, 12000, 0), np.pv(0.07, 20, 12000, 0,
                                                      'end'))
        assert_equal(np.pv(0.07, 20, 12000, 0, 0),
                     np.pv(0.07, 20, 12000, 0, 'end'))

        # begin
        assert_equal(np.fv(0.075, 20, -2000, 0, 1),
                     np.fv(0.075, 20, -2000, 0, 'begin'))
        # end
        assert_equal(np.fv(0.075, 20, -2000, 0),
                     np.fv(0.075, 20, -2000, 0, 'end'))
        assert_equal(np.fv(0.075, 20, -2000, 0, 0),
                     np.fv(0.075, 20, -2000, 0, 'end'))

        # begin
        assert_equal(np.pmt(0.08 / 12, 5 * 12, 15000., 0, 1),
                     np.pmt(0.08 / 12, 5 * 12, 15000., 0, 'begin'))
        # end
        assert_equal(np.pmt(0.08 / 12, 5 * 12, 15000., 0),
                     np.pmt(0.08 / 12, 5 * 12, 15000., 0, 'end'))
        assert_equal(np.pmt(0.08 / 12, 5 * 12, 15000., 0, 0),
                     np.pmt(0.08 / 12, 5 * 12, 15000., 0, 'end'))

        # begin
        assert_equal(np.ppmt(0.1 / 12, 1, 60, 55000, 0, 1),
                     np.ppmt(0.1 / 12, 1, 60, 55000, 0, 'begin'))
        # end
        assert_equal(np.ppmt(0.1 / 12, 1, 60, 55000, 0),
                     np.ppmt(0.1 / 12, 1, 60, 55000, 0, 'end'))
        assert_equal(np.ppmt(0.1 / 12, 1, 60, 55000, 0, 0),
                     np.ppmt(0.1 / 12, 1, 60, 55000, 0, 'end'))

        # begin
        assert_equal(np.ipmt(0.1 / 12, 1, 24, 2000, 0, 1),
                     np.ipmt(0.1 / 12, 1, 24, 2000, 0, 'begin'))
        # end
        assert_equal(np.ipmt(0.1 / 12, 1, 24, 2000, 0),
                     np.ipmt(0.1 / 12, 1, 24, 2000, 0, 'end'))
        assert_equal(np.ipmt(0.1 / 12, 1, 24, 2000, 0, 0),
                     np.ipmt(0.1 / 12, 1, 24, 2000, 0, 'end'))

        # begin
        assert_equal(np.nper(0.075, -2000, 0, 100000., 1),
                     np.nper(0.075, -2000, 0, 100000., 'begin'))
        # end
        assert_equal(np.nper(0.075, -2000, 0, 100000.),
                     np.nper(0.075, -2000, 0, 100000., 'end'))
        assert_equal(np.nper(0.075, -2000, 0, 100000., 0),
                     np.nper(0.075, -2000, 0, 100000., 'end'))
def npv_cost(inflation, num_years, cost):
    npv = np.pv(inflation, num_years, -cost)
    return npv
Ejemplo n.º 12
0
print("3: The company's current price is", "${:,.2f}".format(PV))

#4
PV = 90
R = 0.1
Dyield = 0.5 * R  #the total return on the stock is evenly divided between a capital gains yield and a dividend yield
D1 = PV * Dyield  #dividend for next year is the stock price times dividend yield
D0 = D1 / (1 + Dyield)  #dividend this year
print("4: The current dividend is", "${:,.2f}".format(D0))

#5
import numpy as np
D = -25  #dividend as pmt
N = 7
I = 0.1
PV = np.pv(rate=I, nper=N, pmt=D)
print("5: The current stock price is", "${:,.2f}".format(PV))

#6
D1 = 1.4
G = 0.06
Ired = 0.089  #the require rate of return for Red company
Iyellow = 0.119  #the require rate of return for Yellow company
Iblue = 0.153  #the require rate of return for Blue company
#a
PRed = D1 / (Ired - G)
print("6a: The stock price for Red Inc., is", "${:,.2f}".format(PRed))
#b
PYellow = D1 / (Iyellow - G)
print("6b: The stock price for Yellow Inc., is", "${:,.2f}".format(PYellow))
#c
Ejemplo n.º 13
0
import numpy as np

print "Present value", np.pv(0.03/4, 5 * 4, -10, 1376.09633204)
Ejemplo n.º 14
0
    def assets_required(self):
        rate = self.financial_planning.real_gain()

        return numpy.pv(rate, self.duration_of_usufruct,
                        -self.remain_patrimony * 12)
Ejemplo n.º 15
0
import numpy as np

print(np.fv(0.02, 20 * 12, -100, -100))
print(np.pv(0.02, 20 * 12, -100, 586032.549))
print(np.npv(0.281, [-100, 823, 59, 55, 20]))
print(np.pmt(0.02 / 12, 20 * 12, 1000000))
print(np.ppmt(0.02 / 12, -100, 20 * 12, 1000000))
print(np.ipmt(0.02 / 12, 0.001, 20 * 12, 200000))
print(round(np.irr([-5, 10.5, 1, -8, 1]), 5))
print(np.mirr([-100, 823, 59, 55, 20], -100, -150))
print(np.nper(0.02, -1e7, 1e8))
print(np.rate(0.7, -1e8, 200000, 0))
Ejemplo n.º 16
0
    def test_decimal_with_when(self):
        """Test that decimals are still supported if the when argument is passed"""
        # begin
        assert_equal(
            np.rate(
                Decimal("10"),
                Decimal("20"),
                Decimal("-3500"),
                Decimal("10000"),
                Decimal("1"),
            ),
            np.rate(
                Decimal("10"),
                Decimal("20"),
                Decimal("-3500"),
                Decimal("10000"),
                "begin",
            ),
        )
        # end
        assert_equal(
            np.rate(Decimal("10"), Decimal("20"), Decimal("-3500"),
                    Decimal("10000")),
            np.rate(Decimal("10"), Decimal("20"), Decimal("-3500"),
                    Decimal("10000"), "end"),
        )
        assert_equal(
            np.rate(
                Decimal("10"),
                Decimal("20"),
                Decimal("-3500"),
                Decimal("10000"),
                Decimal("0"),
            ),
            np.rate(Decimal("10"), Decimal("20"), Decimal("-3500"),
                    Decimal("10000"), "end"),
        )

        # begin
        assert_equal(
            np.pv(
                Decimal("0.07"),
                Decimal("20"),
                Decimal("12000"),
                Decimal("0"),
                Decimal("1"),
            ),
            np.pv(Decimal("0.07"), Decimal("20"), Decimal("12000"),
                  Decimal("0"), "begin"),
        )
        # end
        assert_equal(
            np.pv(Decimal("0.07"), Decimal("20"), Decimal("12000"),
                  Decimal("0")),
            np.pv(Decimal("0.07"), Decimal("20"), Decimal("12000"),
                  Decimal("0"), "end"),
        )
        assert_equal(
            np.pv(
                Decimal("0.07"),
                Decimal("20"),
                Decimal("12000"),
                Decimal("0"),
                Decimal("0"),
            ),
            np.pv(Decimal("0.07"), Decimal("20"), Decimal("12000"),
                  Decimal("0"), "end"),
        )

        # begin
        assert_equal(
            np.fv(
                Decimal("0.075"),
                Decimal("20"),
                Decimal("-2000"),
                Decimal("0"),
                Decimal("1"),
            ),
            np.fv(Decimal("0.075"), Decimal("20"), Decimal("-2000"),
                  Decimal("0"), "begin"),
        )
        # end
        assert_equal(
            np.fv(Decimal("0.075"), Decimal("20"), Decimal("-2000"),
                  Decimal("0")),
            np.fv(Decimal("0.075"), Decimal("20"), Decimal("-2000"),
                  Decimal("0"), "end"),
        )
        assert_equal(
            np.fv(
                Decimal("0.075"),
                Decimal("20"),
                Decimal("-2000"),
                Decimal("0"),
                Decimal("0"),
            ),
            np.fv(Decimal("0.075"), Decimal("20"), Decimal("-2000"),
                  Decimal("0"), "end"),
        )

        # begin
        assert_equal(
            np.pmt(
                Decimal("0.08") / Decimal("12"),
                Decimal("5") * Decimal("12"),
                Decimal("15000."),
                Decimal("0"),
                Decimal("1"),
            ),
            np.pmt(
                Decimal("0.08") / Decimal("12"),
                Decimal("5") * Decimal("12"),
                Decimal("15000."),
                Decimal("0"),
                "begin",
            ),
        )
        # end
        assert_equal(
            np.pmt(
                Decimal("0.08") / Decimal("12"),
                Decimal("5") * Decimal("12"),
                Decimal("15000."),
                Decimal("0"),
            ),
            np.pmt(
                Decimal("0.08") / Decimal("12"),
                Decimal("5") * Decimal("12"),
                Decimal("15000."),
                Decimal("0"),
                "end",
            ),
        )
        assert_equal(
            np.pmt(
                Decimal("0.08") / Decimal("12"),
                Decimal("5") * Decimal("12"),
                Decimal("15000."),
                Decimal("0"),
                Decimal("0"),
            ),
            np.pmt(
                Decimal("0.08") / Decimal("12"),
                Decimal("5") * Decimal("12"),
                Decimal("15000."),
                Decimal("0"),
                "end",
            ),
        )

        # begin
        assert_equal(
            np.ppmt(
                Decimal("0.1") / Decimal("12"),
                Decimal("1"),
                Decimal("60"),
                Decimal("55000"),
                Decimal("0"),
                Decimal("1"),
            ),
            np.ppmt(
                Decimal("0.1") / Decimal("12"),
                Decimal("1"),
                Decimal("60"),
                Decimal("55000"),
                Decimal("0"),
                "begin",
            ),
        )
        # end
        assert_equal(
            np.ppmt(
                Decimal("0.1") / Decimal("12"),
                Decimal("1"),
                Decimal("60"),
                Decimal("55000"),
                Decimal("0"),
            ),
            np.ppmt(
                Decimal("0.1") / Decimal("12"),
                Decimal("1"),
                Decimal("60"),
                Decimal("55000"),
                Decimal("0"),
                "end",
            ),
        )
        assert_equal(
            np.ppmt(
                Decimal("0.1") / Decimal("12"),
                Decimal("1"),
                Decimal("60"),
                Decimal("55000"),
                Decimal("0"),
                Decimal("0"),
            ),
            np.ppmt(
                Decimal("0.1") / Decimal("12"),
                Decimal("1"),
                Decimal("60"),
                Decimal("55000"),
                Decimal("0"),
                "end",
            ),
        )

        # begin
        assert_equal(
            np.ipmt(
                Decimal("0.1") / Decimal("12"),
                Decimal("1"),
                Decimal("24"),
                Decimal("2000"),
                Decimal("0"),
                Decimal("1"),
            ).flat[0],
            np.ipmt(
                Decimal("0.1") / Decimal("12"),
                Decimal("1"),
                Decimal("24"),
                Decimal("2000"),
                Decimal("0"),
                "begin",
            ).flat[0],
        )
        # end
        assert_equal(
            np.ipmt(
                Decimal("0.1") / Decimal("12"),
                Decimal("1"),
                Decimal("24"),
                Decimal("2000"),
                Decimal("0"),
            ).flat[0],
            np.ipmt(
                Decimal("0.1") / Decimal("12"),
                Decimal("1"),
                Decimal("24"),
                Decimal("2000"),
                Decimal("0"),
                "end",
            ).flat[0],
        )
        assert_equal(
            np.ipmt(
                Decimal("0.1") / Decimal("12"),
                Decimal("1"),
                Decimal("24"),
                Decimal("2000"),
                Decimal("0"),
                Decimal("0"),
            ).flat[0],
            np.ipmt(
                Decimal("0.1") / Decimal("12"),
                Decimal("1"),
                Decimal("24"),
                Decimal("2000"),
                Decimal("0"),
                "end",
            ).flat[0],
        )
Ejemplo n.º 17
0
 def _calc_mrtg(self, annual_housing_budget, mrtg_int):
     pmt = annual_housing_budget / 12
     return np.pv(mrtg_int / 12, 360, -pmt)
Ejemplo n.º 18
0
举例:某用户去银行存款,假设年利率 3% 、每季度续存金额 10 元、存 5年以及存款 1000 ,则计算 5年后可领取多少金额。
求未来钱数
'''
print(np.fv(0.03 / 4, 5 * 4, -10, -1000))
'''
pv 函数 —— 计算现值( present value present valuepresent value present value present value )是指资产在当前时刻的价值。
现值有以下 4个参数决定 —— 利率、期数每支付金额以及终值
语法格式如下: 语法格式如下: 语法格式如下: numpy.fv(rate, nper , pmt , fv[, when='end’])
#参数: rate raterate:每一期的利率( rate of interest)。
nper nper:期数。
pmt :paymentpayment payment 。每期支付金额
fv : future value,终值。如果是贷款终值为零
when when:{{‘begin’, 1}, {‘end’, 0}},
2举例:某用户去银行存款,假设年利率 3% 、每季度续存金额 10 元、存 5年后可领 1376.0963320,则计算 5年前存取的本金是多 少金额。
'''
print(np.pv(0.03 / 4, 5 * 4, -10, 1376.0963320407982))
'''
np.npv(rate,values)
rate:折现率
values:现金流
03.投资 100,收入39,59,55,20,折现率为28.1% 则净现值为
'''
print(np.npv(0.281, [-100, 39, 59, 55, 20]))
'''
举例:某同学房贷 20 万,准备 15 年还清,利率为 7.5% 7.5% ,则每 月需还贷多少金额?
pmt = np.pmt(0.075/12, 15*12,200000) 计算还款金额
'''
pmt = np.pmt(0.075 / 12, 15 * 12, 200000)
'''
小明房贷 70 万,年利率 4% ,准备还 20 年,
则每月供多少?
# -*- coding: utf-8 -*-
"""
Created on Wed May 19 20:11:05 2021

@author: Dell Wang
"""

import numpy as np 
c=np.array(c)
r=np.array(r)
if when==1:
n=np.arange(1,n+1)
else:
n=np.arange(0,n)
pv=c/(1+r)**n
return pv.sum()
pv1=pv_f(c,r,n,when=1)
print("普通年金现值(年末):%.2f"% pv1)
pv2=pv_f(c,r,n,when=0)
print("预付年金现值(年初):%.2f" % pv2)
import numpy as np
print("numpy自带公式计算(年末):{:.2f}".format(np.pv(r,5,-c),when=0))
print("numpy自带公式计算(年初):{:.2f}".format(np.pv(r,5,-c,when=1)))

Ejemplo n.º 20
0
initial = 1500000
interest = .043

time = 10
compounded = 1

#calculate compound interest
fv = initial * (1 + interest / compounded)**(compounded * time)
print('your future of {} value is    {}'.format(initial, fv))

# #reverse compound interest, also for inflation
iv = initial / (1 + interest / compounded)**(compounded * time)
print('your initial  value was    {}'.format(iv))

investment_1 = np.pv(rate=interest, nper=time, pmt=0,
                     fv=initial)  #calculate inflation
print("Investment 1 is worth " + str(round(-investment_1, 2)) +
      " in today's dollars")

print('............')
print('............')
home_value = 159375000
loan = 127500000
monthly_payment = 1310401
anual_payment = monthly_payment * 12
duration = 20
total_paid = anual_payment * duration

print(
    'loan of {} with monthly payment of 1.310.401 for 20 years for total {}\n which is'
    ' {:.2f} times what you got'.format(loan, total_paid, total_paid / loan))
Ejemplo n.º 21
0
# Python
# > numpy.pv(rate, nper, pmt, fv=0.0, when='end')
#
# ## 引数
# * rate (必須): 利率
# * nper (必須): 複利計算期間数 (支払回数)
# * pmt (必須): 毎回の支払額
# * fv : 将来価値 (返済の場合: 0, 貯蓄の場合: 積立目標額)
# * when: 支払期日、いつ支払いが行われるか。 (end/0: 各期の期末, start/1: 各期の機種)
#
# ## 利用例
# 年利 5% で 10 年間、毎月 100 ドル支払い、15692.93 ドル積み立て目標での現在価値。

# In[4]:

print(np.pv(0.05 / 12, 10 * 12, -100, 15692.93))

# # 正味現在価値 (純現在価値, NPV: Net Present Value)
# `np.npv()` にて、正味現在価値を算出します。
# Excel には、NPV 関数として実装されています。
#
# ## 使い方
# > numpy.npv(rate, values)
#
# ## 引数
# * rate (必須): 割引率
# * values (必須): 一連のキャッシュフロー額
#
# ## 利用例
# 割引率 28.1% に対して、100 万円の投資と毎年、39, 59, 55, 20 万円の収益が得られた場合の正味現在価値
Ejemplo n.º 22
0
    # Print the results at each period
    print("Period " + str(i) + ": Current Investment Balance: " + \
          str(round(investment_portfolio[i], 2)) + \
          " | Savings Account: " + str(round(cumulative_savings_new[i], 2)) + \
          " | Net Worth: " + str(round(net_worth[i], 2)) \
         )

# Plot your forecasted cumulative savings vs investments and net worth
plt.figure()
plt.plot(investment_portfolio, color='red', label='investment portfolio')
plt.plot(cumulative_savings_new, color='blue', label='cumulative savings new')
plt.plot(net_worth, color='green', label='net worth')
plt.legend(loc=2)
plt.show()

# Set your future net worth
future_net_worth = 900000

# Set the annual inflation rate to 2.5%
annual_inflation = 0.025

# Calculate the present value of your terminal wealth over 15 years
inflation_adjusted_net_worth = np.pv(rate=annual_inflation,
                                     nper=15,
                                     pmt=0,
                                     fv=-1 * future_net_worth)
print("Your inflation-adjusted net worth: $" +
      str(round(inflation_adjusted_net_worth, 2)))

#plt.close('all')
Ejemplo n.º 23
0
 def test_pv_decimal(self):
     assert_equal(
         np.pv(Decimal("0.07"), Decimal("20"), Decimal("12000"),
               Decimal("0")),
         Decimal("-127128.1709461939327295222005"),
     )
Ejemplo n.º 24
0
 def test_pv(self):
     assert_almost_equal(np.pv(0.07, 20, 12000, 0), -127128.17, 2)
@author: ESAccount24
"""

# -*- coding: utf-8 -*-
"""
Created on Sat Sep 26 11:34:21 2015

@author: ESAccount24
"""
#financial institutions
import numpy as np
import scipy.optimize as sp
def myfnc(x):
    return np.pv(x,2,0,125.44)+100.0
    
futval=np.fv(0.12,2,0,-100.0)
print futval
prval=np.pv(0.12,2,0,125.44)
print prval

nperiods=np.nper(0.12,0,-100.0,125.44)
print nperiods

intrate=np.rate(2,0,-100,125.44)
print intrate

initialRateGuess=0.134

#goalseek
#find interest rate that satisfies euqation connecting pv, fv, and nper
print sp.fsolve(myfnc,initialRateGuess)
Ejemplo n.º 26
0
 def test_pv(self):
     assert_almost_equal(np.pv(.10, 12, -100, 100), 649.51, 2)
Ejemplo n.º 27
0
import numpy as np

np.pv(0.05 / 12, 10 * 12, -100, 15692.93)
a = np.array((0.05, 0.04, 0.03)) / 12
np.pv(a, 10 * 12, -100, 15692.93)
Ejemplo n.º 28
0
 def Present_Value():
     a = np.pv(eval(e1.get()), eval(e2.get()), eval(e3.get()),
               eval(e4.get()))
     a = 0 - a
     v1.set(a)
 def loanCal(self):
     nPeriod12 = self.durationCal() * 12 #loan duration in months
     return abs(np.pv(0.02/12, nPeriod12, self.pmtCal(), fv=0, when = 'end'))    
Ejemplo n.º 30
0
# The purpose of this program is to evaluate the best decision between three options
# The decision considers a 5 year term with a $10,000 residual future state value
# Option 1: Purchase a car outright using an interest rate pegged to a mortage rate
# Option 2: Use a novated lease for a one year term
# Option 3: Use a novated lease for a two year term

# import appropriate packages
import numpy as np

# Key parameters
purchase_price_GST = 40000  # inclusive of GST
residual_value = 10000  # value of vehicle after 10 years (estimated)
lease_price_NOGST = 36000
mortgate_int = 0.05 / 12
periods = 5 * 12
lease_costs_1 = np.array([350, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
lease_costs_2 = np.array(
    [350, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

# Calculate the NPV of purchasing the car outright
option_1 = np.pv(rate=mortgate_int, nper=periods, pmt=0, fv=residual_value)
print("Option 1 is worth " + str(round(-option_1, 2)) + " in today's dollars")
Ejemplo n.º 31
0
    def do_proforma(proposal, proposal_component):
        p = proposal
        c = proposal_component
        max_periods = max_periods_of_sale + asscalar(p['sales_start_period'])
        revenues = zeros(max_periods)
        costs = zeros(max_periods)
        #cash_flow = zeros(max_periods)

        construction_loan_balance = p['construction_cost'] * construction_loan_size
        perm_loan_size = 0
        perm_loan_interest_payment = 0
        perm_loan_repayment = 0
        perm_loan_proceeds = 0.0

        full_rent_periods = 0
        sold_for_rent = 0
        component_sales_revenue = c['sales_revenue'].copy()
        component_rent_revenue = c['rent_revenue_per_period'].copy()
        component_leases_revenue = c['leases_revenue_per_period'].copy()
        construction_periods = p['sales_start_period'] - p['construction_start_period']
        
        for period in arange(max_periods):
            
            if period == 1:
                land_equity = p['land_cost']
                costs[period] += land_equity            
            
            elif component_rent_revenue.sum() >= c['rent_revenue'].sum() and \
                component_leases_revenue.sum() >= c['leases_revenue'].sum():
                full_rent_periods += 1
            
            if period < p['sales_start_period']:
                #revenues
                public_contribution = 0 if p['public_contribution'] == 0 \
                                        else p['public_contribution'] / \
                                             float(construction_periods)
                
                sales_revenue = 0
                rent_revenue = 0 
                leases_revenue = 0
                revenues[period] += public_contribution

                #costs
                operating_cost = 0
                vacancy = 0
                tax = p['property_tax'] * p['land_cost']
                construction_equity = p['construction_cost'] * (1 - construction_loan_size) \
                        / (p['sales_start_period'] - 1)
                construction_loan_interest_payment = construction_loan_balance * construction_loan_rate
                construction_loan_repayment = revenues[period] \
                        if construction_loan_balance > revenues[period] \
                        else construction_loan_balance
                costs[period] += tax + construction_equity + \
                     construction_loan_interest_payment + construction_loan_repayment
                construction_loan_balance -= construction_loan_repayment
            else:
                if any(component_sales_revenue):
                    # TODO this would not work when we do proforma on multiple proposals at once
                    sales_revenue = np.min(column_stack((c['sales_absorption'],
                                                          component_sales_revenue)),
                                            axis=1
                                               ).sum()
                    component_sales_revenue -= c['sales_absorption']
                    np.clip(component_sales_revenue, 
                            0, component_sales_revenue.max(),
                            out=component_sales_revenue)
                else:
                    sales_revenue = 0
                if sales_revenue < 0: sales_revenue = 0
                
                # before reaching full occupancy for rent property
                if not sold_for_rent and any(component_rent_revenue <= c['rent_revenue']):
                    rent_revenue = np.min(column_stack((c['rent_revenue'],
                                                        component_rent_revenue)),
                                          axis=1
                                          )
                    operating_cost = (rent_revenue * c['operating_cost']).sum()
                    vacancy = (rent_revenue * c['vacancy_rates']).sum()
                    rent_revenue = rent_revenue.sum()                    
                    component_rent_revenue += c['rent_revenue_per_period']
                    np.clip(component_rent_revenue, 
                            0, c['rent_revenue'],
                            out=component_rent_revenue)
                    
                if not sold_for_rent and any(component_leases_revenue <= c['leases_revenue']):
                    leases_revenue = np.min(column_stack((c['leases_revenue'],
                                                          component_leases_revenue)),
                                            axis=1
                                            )
                    operating_cost += (leases_revenue * c['operating_cost']).sum()
                    vacancy += (leases_revenue * c['vacancy_rates']).sum()
                    leases_revenue = leases_revenue.sum()
                    component_leases_revenue += c['leases_revenue_per_period']
                    np.clip(component_leases_revenue, 
                            0, c['leases_revenue'],
                            out=component_leases_revenue)                    
 
                #revenues
                if not sold_for_rent:
                    revenues[period] += sales_revenue + rent_revenue + leases_revenue
                else:
                    revenues[period] = sales_revenue
                    if revenues[period] == 0:
                        break                

                #costs
                taxable_proportion = p['rent_sqft'] / p['total_sqft'].astype(float32)
                tax = p['property_tax'] * (p['land_cost'] + p['construction_cost']) * taxable_proportion
                insurance = p['rent_sqft'] * property_insurance
                construction_equity = 0
                construction_loan_interest_payment = construction_loan_balance * construction_loan_rate
                construction_loan_repayment = revenues[period] \
                        if construction_loan_balance > revenues[period] \
                        else construction_loan_balance
                
                #adjustment to revenues/costs
                for_rent_noi = rent_revenue + leases_revenue - tax - insurance - operating_cost - vacancy
                meets_perm_load_occupancy_threshold = rent_revenue + leases_revenue > \
                                                               ( p['rent_revenue'] + p['leases_revenue']) * \
                                                               perm_load_occupancy_threshold
                
                if perm_loan_size == 0 and \
                   for_rent_noi > 0 and \
                   meets_perm_load_occupancy_threshold:
                    perm_loan_size = min((for_rent_noi / cap_rate) * ltv_max,
                                          -np.pv(perm_loan_rate, 
                                                perm_loan_term, 
                                                for_rent_noi / dcr_max)
                                       )
                    perm_loan_proceeds = perm_loan_size
                    revenues[period] += perm_loan_proceeds

                if perm_loan_size > 0:
                    perm_loan_interest_payment = -np.pmt(perm_loan_rate, perm_loan_term, perm_loan_size)
                
                if not sold_for_rent:
                    costs[period] += tax + insurance + operating_cost + vacancy + \
                            construction_loan_interest_payment + construction_loan_repayment + \
                            perm_loan_interest_payment
                else:
                    costs[period] = 0
                
                construction_loan_balance -= construction_loan_repayment
                if DEBUG: print period, sales_revenue, full_rent_periods, for_rent_seasoning_threshold 
                if full_rent_periods > for_rent_seasoning_threshold+1 and \
                   sales_revenue <= 0 and \
                   not sold_for_rent:
                    #sell_for_rent = 1
                    perm_loan_repayment = perm_loan_size
                    for_rent_sale = for_rent_noi / cap_rate
                    revenues[period] += for_rent_sale
                    costs[period] += perm_loan_repayment
                    sold_for_rent = 1
                    #break

        if DEBUG: print "REVENUES:", revenues
        costs = costs * (1.0-p['costdiscount'])
        if DEBUG: print "COSTS:", costs
        cash_flow = (revenues - costs)[1:period]
        npv = np.npv(discount_rate, cash_flow)
        if DEBUG: print "CASHFLOW:", cash_flow
        if DEBUG: print "NPV:", npv
        irr = np.irr(cash_flow)

        return asarray(npv)
print("\n0.PV\n1.FV\n2.Rate\n3.N\n4.PMT")
choice = input("\nChoose what solve to for: ")

if(choice=="0"):
    print("\nEnter values as prompted")
    print("Enter interest rate as decimal")
    n = input("\nEnter times compounded: ")
    rate = input("\nEnter rate as decimal: ")
    fv = input("\nEnter FV: ")
    pmt = input("\nEnter Pmt: ")
    time_range = input("\nEnter number of years: ")
    if(float(time_range)==0 or float(time_range)<0):
        print("\nError: Must be a minimum of 1 year")
    else:
        pv=np.pv(float(rate)/float(n), float(time_range)*float(n), float(pmt), float(fv))
        print("PV: "+str(pv))
        
elif(choice=="1"):
    print("\nEnter values as prompted")
    print("Enter interest rate as decimal")
    n = input("\nEnter times compounded: ")
    rate = input("\nEnter rate as decimal: ")
    pv = input("\nEnter PV: ")
    pmt = input("\nEnter Pmt: ")
    time_range = input("\nEnter number of years: ")
    if(float(time_range)==0 or float(time_range)<0):
        print("\nError: Must be a minimum of 1 year")
    else:
        fv=np.fv(float(rate)/float(n), float(time_range)*float(n), float(pmt), float(pv))
        print("FV: "+str(fv))
Ejemplo n.º 33
0
import numpy as np
# 终值 = np.fv(利率, 期数, 每期支付, 现值)
# 将1000元以1%的年利率存入银行5年,每年加存100元,
# 到期后本息合计多少钱?
fv = np.fv(0.01, 5, -00, -1000000)
print(round(fv, 2))
# 现值 = np.pv(利率, 期数, 每期支付, 终值)
# 将多少钱以1%的年利率存入银行5年,每年加存100元,
# 到期后本息合计fv元?
pv = np.pv(0.01, 5, -100, fv)
print(pv)
# 净现值 = np.npv(利率, 现金流)
# 将1000元以1%的年利率存入银行5年,每年加存100元,
# 相当于一次性存入多少钱?
npv = np.npv(0.01, [-1000, -100, -100, -100, -100, -100])
print(round(npv, 2))
fv = np.fv(0.01, 5, 0, npv)
print(round(fv, 2))
# 内部收益率 = np.irr(现金流)
# 将1000元存入银行5年,以后逐年提现100元、200元、
# 300元、400元、500元,银行利率达到多少,可在最后
# 一次提现后偿清全部本息,即净现值为0元?
irr = np.irr([-1000, 100, 200, 300, 400, 500])
print(round(irr, 2))
npv = np.npv(irr, [-1000, 100, 200, 300, 400, 500])
print(npv)
# 每期支付 = np.pmt(利率, 期数, 现值)
# 以1%的年利率从银行贷款1000元,分5年还清,
# 平均每年还多少钱?
pmt = np.pmt(0.01, 5, 1000000)
print(round(pmt, 2))
Näide 2
Kui suur peab olema investeeringu hetkeväärtus, et 10 aasta päras oleks
kogunenud 14485.09€, kui aastane intressimäär on 3.5% ning me lisame
investeeringule iga kuu 100€? Kui suur peab olema alginvesteering, et selline
summa koguneks 5, 6, 7, 8 või 9 aastaga?
------------------------------------------------------------------------------
"""

print("\nNäide 2\n-------\n")

RATE = 0.035 / 12  # 3.5% aastas, 3.5%/12 perioodis
PERIOD = 10*12  # 10 aastat
PAYMENT = -100  # maksame 100€ kuus, '-' tähendab raha väljavoolu
FV = 14485.09  # soovitud tulemus

PRESENT_VALUE = np.pv(RATE, PERIOD, PAYMENT, FV, when='end')
print("Et toota {0}€, peaks investeeringu hetkeväärtus olema {1:.2f}€."
      .format(FV, -PRESENT_VALUE)  # '-' tähistab väljaminekut
      )

PERIODS = np.array([5, 6, 7, 8, 9])
PRESENT_VALUES = np.pv(RATE, PERIODS*12, PAYMENT, FV, when='end')
for period, pv in zip(PERIODS, PRESENT_VALUES):
    print("{0} aasta korral peaks investeeringu hetkeväärtus olema {1:.2f}€."
          .format(period, -pv)  # '-' tähistab väljaminekut
          )

"""
------------------------------------------------------------------------------
nper (net present value) -- perioodiliste maksete arvu arvutamine
nper(rate, pmt, pv, fv=0, when='end')
Ejemplo n.º 35
0
 def test_pv(self):
     assert_almost_equal(np.pv(.10,12,-100,100), 649.51, 2)
Ejemplo n.º 36
0
 def get_required_portfolio(self):
     amount = self.current_rate * self.portfolio.value
     pv = numpy.pv(float(self.get_rate()), self.get_life_expectancy(), float(-amount), when='beginning')
     return Decimal(pv)
Ejemplo n.º 37
0
def tvmm(pval=None,
         fval=None,
         pmt=None,
         nrate=None,
         nper=None,
         due=0,
         pyr=1,
         noprint=True):
    """Computes the missing argument (set to ``None``) in a model relating the
    present value, the future value, the periodic payment, the number of
    compounding periods and the nominal interest rate in a cashflow.

    Args:
        pval (float, list): Present value.
        fval (float, list): Future value.
        pmt (float, list): Periodic payment.
        nrate (float, list): Nominal interest rate per year.
        nper (int, list): Number of compounding periods.
        due (int): When payments are due.
        pyr (int, list): number of periods per year.
        noprint (bool): prints enhanced output

    Returns:
        Argument set to None in the function call.


    **Details**

    The ``tvmmm`` function computes and returns the missing value (``pmt``, ``fval``,
    ``pval``, ``nper``, ``nrate``) in a model relating a finite sequence  of payments
    made at the beginning or at the end of each period, a present value, a future value,
    and a nominal interest rate. The time intervals between consecutive payments are
    assumed to be equal. For internal computations, the effective interest rate per
    period is calculated as ``nrate / pyr``.


    **Examples**

    This example shows how to find different values for a loan of 5000, with a
    monthly payment of 130 at the end of the month, a life of 48 periods, and a
    interest rate of 0.94 per month (equivalent to a nominal interest
    rate of 11.32%). For a loan, the future value is 0.

    * Monthly payments: Note that the parameter ``pmt`` is set to ``None``.

    >>> tvmm(pval=5000, nrate=11.32, nper=48, fval=0, pyr=12) # doctest: +ELLIPSIS
    -130.00...


    When the parameter ``noprint`` is set to ``False``, a user friendly table with
    the data computed by the function is print.

    >>> tvmm(pval=5000, nrate=11.32, nper=48, fval=0, pyr=12, noprint=False) # doctest: +ELLIPSIS
    Present Value: .......  5000.00
    Future Value: ........     0.00
    Payment: .............  -130.01
    Due: .................      END
    No. of Periods: ......    48.00
    Compoundings per Year:    12
    Nominal Rate: .......     11.32
    Effective Rate: .....     11.93
    Periodic Rate: ......      0.94


    * Future value:

    >>> tvmm(pval=5000, nrate=11.32, nper=48, pmt=pmt, fval=None, pyr=12) # doctest: +ELLIPSIS
    -0.0...

    * Present value:

    >>> tvmm(nrate=11.32, nper=48, pmt=pmt, fval = 0.0, pval=None, pyr=12) # doctest: +ELLIPSIS
    5000...

    All the arguments support lists as inputs. When a argument is a list and the
    ``noprint`` is set to ``False``, a table with the data is print.

    >>> tvmm(pval=[5, 500, 5], nrate=11.32, nper=48, fval=0, pyr=12, noprint=False) # doctest: +ELLIPSIS
    #   pval   fval    pmt   nper  nrate  erate  prate due
    ------------------------------------------------------
    0   5.00   0.00  -0.13  48.00  11.32  11.93   0.94 END
    1 500.00   0.00  -0.13  48.00  11.32  11.93   0.94 END
    2   5.00   0.00  -0.13  48.00  11.32  11.93   0.94 END


    * Interest rate:

    >>> tvmm(pval=5000, nper=48, pmt=pmt, fval = 0.0, pyr=12) # doctest: +ELLIPSIS
    11.32...

    * Number of periods:

    >>> tvmm(pval=5000, nrate=11.32/12, pmt=pmt, fval=0.0) # doctest: +ELLIPSIS
    48.0...


    """

    #pylint: disable=too-many-arguments
    #pylint: disable=too-many-branches

    numnone = 0
    numnone += 1 if pval is None else 0
    numnone += 1 if fval is None else 0
    numnone += 1 if nper is None else 0
    numnone += 1 if pmt is None else 0
    numnone += 1 if nrate is None else 0

    if numnone > 1:
        raise ValueError('One of the params must be set to None')

    if numnone == 0:
        pmt = None

    if pmt == 0.0:
        pmt = 0.0000001

    nrate = numpy.array(nrate)

    if pval is None:
        result = numpy.pv(rate=nrate / 100 / pyr,
                          nper=nper,
                          fv=fval,
                          pmt=pmt,
                          when=due)
    elif fval is None:
        result = numpy.fv(rate=nrate / 100 / pyr,
                          nper=nper,
                          pv=pval,
                          pmt=pmt,
                          when=due)
    elif nper is None:
        result = numpy.nper(rate=nrate / 100 / pyr,
                            pv=pval,
                            fv=fval,
                            pmt=pmt,
                            when=due)
    elif pmt is None:
        result = numpy.pmt(rate=nrate / 100 / pyr,
                           nper=nper,
                           pv=pval,
                           fv=fval,
                           when=due)
    else:
        result = numpy.rate(pv=pval, nper=nper, fv=fval, pmt=pmt,
                            when=due) * 100 * pyr

    if noprint is True:
        if isinstance(result, numpy.ndarray):
            return result.tolist()
        return result

    nrate = nrate.tolist()

    if pval is None:
        pval = result
    elif fval is None:
        fval = result
    elif nper is None:
        nper = result
    elif pmt is None:
        pmt = result
    else:
        nrate = result

    params = _vars2list([pval, fval, nper, pmt, nrate])
    pval = params[0]
    fval = params[1]
    nper = params[2]
    pmt = params[3]
    nrate = params[4]

    # raise ValueError(nrate.__repr__())

    erate, prate = iconv(nrate=nrate, pyr=pyr)

    if len(pval) == 1:
        if pval is not None:
            print('Present Value: ....... {:8.2f}'.format(pval[0]))
        if fval is not None:
            print('Future Value: ........ {:8.2f}'.format(fval[0]))
        if pmt is not None:
            print('Payment: ............. {:8.2f}'.format(pmt[0]))
        if due is not None:
            print('Due: .................      {:s}'.format('END' if due ==
                                                            0 else 'BEG'))
        print('No. of Periods: ...... {:8.2f}'.format(nper[0]))
        print('Compoundings per Year: {:>5d}'.format(pyr))
        print('Nominal Rate: .......  {:8.2f}'.format(nrate[0]))
        print('Effective Rate: .....  {:8.2f}'.format(erate))
        print('Periodic Rate: ......  {:8.2f}'.format(prate))

    else:
        if due == 0:
            sdue = 'END'
            txtpmt = []
            for item, _ in enumerate(pval):
                txtpmt.append(pmt[item][-1])
        else:
            sdue = 'BEG'
            txtpmt = []
            for item, _ in enumerate(pval):
                txtpmt.append(pmt[item][0])

        maxlen = 5
        for value1, value2, value3, value4 in zip(pval, fval, txtpmt, nper):
            maxlen = max(maxlen, len('{:1.2f}'.format(value1)))
            maxlen = max(maxlen, len('{:1.2f}'.format(value2)))
            maxlen = max(maxlen, len('{:1.2f}'.format(value3)))
            maxlen = max(maxlen, len('{:1.2f}'.format(value4)))

        len_aux = len('{:d}'.format(len(pval)))

        fmt_num = ' {:' + '{:d}'.format(maxlen) + '.2f}'
        fmt_num = '{:<' + '{:d}'.format(
            len_aux) + 'd}' + fmt_num * 7 + ' {:3s}'
        # fmt_shr = '{:' + '{:d}'.format(len_aux) + 's}'
        fmt_hdr = ' {:>' + '{:d}'.format(maxlen) + 's}'
        fmt_hdr = '{:' + '{:d}'.format(len_aux) + 's}' + fmt_hdr * 7 + ' due'

        txt = fmt_hdr.format('#', 'pval', 'fval', 'pmt', 'nper', 'nrate',
                             'erate', 'prate')
        print(txt)
        print('-' * len_aux + '-' * maxlen * 7 + '-' * 7 + '----')
        for item, _ in enumerate(pval):
            print(
                fmt_num.format(item, pval[item], fval[item], txtpmt[item],
                               nper[item], nrate[item], erate[item],
                               prate[item], sdue))
Ejemplo n.º 38
0
def main():
    # Sweep over
    # (cost per flight w/ 1st stage reuse)
    # / (cost per flight of all-expendable launch vehicle)
    # [units: dimensionless].

    # Figure format switch - paper or presentation?

    fig_format = 'presentation'
    if fig_format == 'presentation':
        fontsize = 14
    if fig_format == 'paper':
        fontsize = 17

    cpf_ratio = np.linspace(0, 1)

    # Launch rate [units: year**-1].
    launch_rates = [1, 5, 10, 20, 40]

    # Discount rate (per year)
    discount_rate_annual = 0.20

    # Horizon [units: year].
    horizon = 20

    # Present value of savings from reuse
    # [units: multiples of (cost per flight of all-expendable launch vehicle)]
    pres_val = np.zeros(len(cpf_ratio))

    plt.figure(figsize=(8, 6))
    for launch_rate in launch_rates:
        # Discount rate per "payment period", i.e. per
        # interval between launches.
        discount_rate_per_period = discount_rate_annual / launch_rate

        for i in range(len(cpf_ratio)):
            pres_val[i] = np.pv(
                rate=discount_rate_per_period,
                nper=launch_rate * horizon,
                pmt=cpf_ratio[i] - 1,
                when='begin',
            )

        plt.plot(cpf_ratio, pres_val, label='{:.0f}'.format(launch_rate))

    # Highlight credible range of cpf ratio
    # These ranges were computed by lvreuse.analysis.combined.cost_ratio.py,
    # https://github.mit.edu/mvernacc/1st-stage-return/blob/1d0a2a4421405421b4fb6cac9cb14ff232de4fd0/lvreuse/analysis/combined/cost_ratio.py
    # For downrange propulsive landing, LEO mission, kerosene technology.
    # For medium-heavy launch vehicles (10 to 100 Mg payload to LEO)
    plt.axvspan(xmin=0.39, xmax=0.68, color='green', alpha=0.1)
    # For small lauch vehicles (100 kg to LEO)
    plt.axvspan(xmin=0.80, xmax=0.96, color='green', alpha=0.1)

    # Highlight credible range of dev costs
    # e.g. for a eelv-size vehicle, cpf is likely $50M, and
    # reusability development probably costs $400M to $3B
    # so credible range is 8 to 60
    # Sources:
    #   Low bound on dev cost: https://www.nasa.gov/sites/default/files/files/Section403(b)CommercialMarketAssessmentReportFinal.pdf
    #   High bound on dev cost: guess at Blue Origin dev. spending based on J. Bezos'
    #       sales of Amazon stock.
    plt.axhspan(ymin=8, ymax=60, color='grey', alpha=0.2)

    plt.xlim([0, 1])
    plt.ylim([0, 100])
    plt.xticks(fontsize=0.8 * fontsize)
    plt.yticks(fontsize=0.8 * fontsize)
    plt.xlabel('Cost p.f. w/ 1st stage reuse / cost p.f. expendable [-]',
               fontsize=fontsize)
    plt.ylabel('Present value of savings / cost p.f. expendable [-]',
               fontsize=fontsize)
    plt.title('Present value of reuse cost per flight savings' +
              '\n {:.0f} %/year discount rate, {:.0f} year horizon'.format(
                  discount_rate_annual * 100, horizon),
              fontsize=fontsize)
    plt.tight_layout()
    plt.savefig(os.path.join('plots', 'reuse_npv.png'), dpi=200)

    plt.legend(title='Launch rate / year', fontsize=0.8 * fontsize)
    plt.show()
Ejemplo n.º 39
0
    def test_decimal_with_when(self):
        """Test that decimals are still supported if the when argument is passed"""
        # begin
        assert_equal(
            np.rate(Decimal('10'), Decimal('20'), Decimal('-3500'),
                    Decimal('10000'), Decimal('1')),
            np.rate(Decimal('10'), Decimal('20'), Decimal('-3500'),
                    Decimal('10000'), 'begin'))
        # end
        assert_equal(
            np.rate(Decimal('10'), Decimal('20'), Decimal('-3500'),
                    Decimal('10000')),
            np.rate(Decimal('10'), Decimal('20'), Decimal('-3500'),
                    Decimal('10000'), 'end'))
        assert_equal(
            np.rate(Decimal('10'), Decimal('20'), Decimal('-3500'),
                    Decimal('10000'), Decimal('0')),
            np.rate(Decimal('10'), Decimal('20'), Decimal('-3500'),
                    Decimal('10000'), 'end'))

        # begin
        assert_equal(
            np.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'),
                  Decimal('0'), Decimal('1')),
            np.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'),
                  Decimal('0'), 'begin'))
        # end
        assert_equal(
            np.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'),
                  Decimal('0')),
            np.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'),
                  Decimal('0'), 'end'))
        assert_equal(
            np.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'),
                  Decimal('0'), Decimal('0')),
            np.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'),
                  Decimal('0'), 'end'))

        # begin
        assert_equal(
            np.fv(Decimal('0.075'), Decimal('20'), Decimal('-2000'),
                  Decimal('0'), Decimal('1')),
            np.fv(Decimal('0.075'), Decimal('20'), Decimal('-2000'),
                  Decimal('0'), 'begin'))
        # end
        assert_equal(
            np.fv(Decimal('0.075'), Decimal('20'), Decimal('-2000'),
                  Decimal('0')),
            np.fv(Decimal('0.075'), Decimal('20'), Decimal('-2000'),
                  Decimal('0'), 'end'))
        assert_equal(
            np.fv(Decimal('0.075'), Decimal('20'), Decimal('-2000'),
                  Decimal('0'), Decimal('0')),
            np.fv(Decimal('0.075'), Decimal('20'), Decimal('-2000'),
                  Decimal('0'), 'end'))

        # begin
        assert_equal(
            np.pmt(
                Decimal('0.08') / Decimal('12'),
                Decimal('5') * Decimal('12'), Decimal('15000.'), Decimal('0'),
                Decimal('1')),
            np.pmt(
                Decimal('0.08') / Decimal('12'),
                Decimal('5') * Decimal('12'), Decimal('15000.'), Decimal('0'),
                'begin'))
        # end
        assert_equal(
            np.pmt(
                Decimal('0.08') / Decimal('12'),
                Decimal('5') * Decimal('12'), Decimal('15000.'), Decimal('0')),
            np.pmt(
                Decimal('0.08') / Decimal('12'),
                Decimal('5') * Decimal('12'), Decimal('15000.'), Decimal('0'),
                'end'))
        assert_equal(
            np.pmt(
                Decimal('0.08') / Decimal('12'),
                Decimal('5') * Decimal('12'), Decimal('15000.'), Decimal('0'),
                Decimal('0')),
            np.pmt(
                Decimal('0.08') / Decimal('12'),
                Decimal('5') * Decimal('12'), Decimal('15000.'), Decimal('0'),
                'end'))

        # begin
        assert_equal(
            np.ppmt(
                Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('60'),
                Decimal('55000'), Decimal('0'), Decimal('1')),
            np.ppmt(
                Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('60'),
                Decimal('55000'), Decimal('0'), 'begin'))
        # end
        assert_equal(
            np.ppmt(
                Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('60'),
                Decimal('55000'), Decimal('0')),
            np.ppmt(
                Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('60'),
                Decimal('55000'), Decimal('0'), 'end'))
        assert_equal(
            np.ppmt(
                Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('60'),
                Decimal('55000'), Decimal('0'), Decimal('0')),
            np.ppmt(
                Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('60'),
                Decimal('55000'), Decimal('0'), 'end'))

        # begin
        assert_equal(
            np.ipmt(
                Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('24'),
                Decimal('2000'), Decimal('0'), Decimal('1')).flat[0],
            np.ipmt(
                Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('24'),
                Decimal('2000'), Decimal('0'), 'begin').flat[0])
        # end
        assert_equal(
            np.ipmt(
                Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('24'),
                Decimal('2000'), Decimal('0')).flat[0],
            np.ipmt(
                Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('24'),
                Decimal('2000'), Decimal('0'), 'end').flat[0])
        assert_equal(
            np.ipmt(
                Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('24'),
                Decimal('2000'), Decimal('0'), Decimal('0')).flat[0],
            np.ipmt(
                Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('24'),
                Decimal('2000'), Decimal('0'), 'end').flat[0])
Ejemplo n.º 40
0
    def test_when(self):
        # begin
        assert_equal(np.rate(10, 20, -3500, 10000, 1),
                     np.rate(10, 20, -3500, 10000, 'begin'))
        # end
        assert_equal(np.rate(10, 20, -3500, 10000),
                     np.rate(10, 20, -3500, 10000, 'end'))
        assert_equal(np.rate(10, 20, -3500, 10000, 0),
                     np.rate(10, 20, -3500, 10000, 'end'))

        # begin
        assert_equal(np.pv(0.07, 20, 12000, 0, 1),
                     np.pv(0.07, 20, 12000, 0, 'begin'))
        # end
        assert_equal(np.pv(0.07, 20, 12000, 0),
                     np.pv(0.07, 20, 12000, 0, 'end'))
        assert_equal(np.pv(0.07, 20, 12000, 0, 0),
                     np.pv(0.07, 20, 12000, 0, 'end'))

        # begin
        assert_equal(np.fv(0.075, 20, -2000, 0, 1),
                     np.fv(0.075, 20, -2000, 0, 'begin'))
        # end
        assert_equal(np.fv(0.075, 20, -2000, 0),
                     np.fv(0.075, 20, -2000, 0, 'end'))
        assert_equal(np.fv(0.075, 20, -2000, 0, 0),
                     np.fv(0.075, 20, -2000, 0, 'end'))

        # begin
        assert_equal(np.pmt(0.08 / 12, 5 * 12, 15000., 0, 1),
                     np.pmt(0.08 / 12, 5 * 12, 15000., 0, 'begin'))
        # end
        assert_equal(np.pmt(0.08 / 12, 5 * 12, 15000., 0),
                     np.pmt(0.08 / 12, 5 * 12, 15000., 0, 'end'))
        assert_equal(np.pmt(0.08 / 12, 5 * 12, 15000., 0, 0),
                     np.pmt(0.08 / 12, 5 * 12, 15000., 0, 'end'))

        # begin
        assert_equal(np.ppmt(0.1 / 12, 1, 60, 55000, 0, 1),
                     np.ppmt(0.1 / 12, 1, 60, 55000, 0, 'begin'))
        # end
        assert_equal(np.ppmt(0.1 / 12, 1, 60, 55000, 0),
                     np.ppmt(0.1 / 12, 1, 60, 55000, 0, 'end'))
        assert_equal(np.ppmt(0.1 / 12, 1, 60, 55000, 0, 0),
                     np.ppmt(0.1 / 12, 1, 60, 55000, 0, 'end'))

        # begin
        assert_equal(np.ipmt(0.1 / 12, 1, 24, 2000, 0, 1),
                     np.ipmt(0.1 / 12, 1, 24, 2000, 0, 'begin'))
        # end
        assert_equal(np.ipmt(0.1 / 12, 1, 24, 2000, 0),
                     np.ipmt(0.1 / 12, 1, 24, 2000, 0, 'end'))
        assert_equal(np.ipmt(0.1 / 12, 1, 24, 2000, 0, 0),
                     np.ipmt(0.1 / 12, 1, 24, 2000, 0, 'end'))

        # begin
        assert_equal(np.nper(0.075, -2000, 0, 100000., 1),
                     np.nper(0.075, -2000, 0, 100000., 'begin'))
        # end
        assert_equal(np.nper(0.075, -2000, 0, 100000.),
                     np.nper(0.075, -2000, 0, 100000., 'end'))
        assert_equal(np.nper(0.075, -2000, 0, 100000., 0),
                     np.nper(0.075, -2000, 0, 100000., 'end'))
Ejemplo n.º 41
0
 def test_pv_decimal(self):
     assert_equal(
         np.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'),
               Decimal('0')), Decimal('-127128.1709461939327295222005'))
Ejemplo n.º 42
0
 def test_pv_decimal(self):
     assert_equal(np.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'), Decimal('0')),
                  Decimal('-127128.1709461939327295222005'))
def myfnc(x):
    return np.pv(x,2,0,125.44)+100.0
import numpy as np

# Calculate investment_1
investment_1 = np.fv(rate=0.08, nper=10, pmt=0, pv=-10000)
print("Investment 1 will yield a total of $" + str(round(investment_1, 2)) +
      " in 10 years")

# Calculate investment_2
investment_1_discounted = np.pv(rate=0.03, nper=10, pmt=0, fv=investment_1)
print("After adjusting for inflation, investment 1 is worth $" +
      str(round(-investment_1_discounted, 2)) + " in today's dollars")
Ejemplo n.º 45
0
 def desired_cash(self):
     return np.pv(self.interest, self.years_in_retire,
                  -self.annual_spend_retire, 0)
Ejemplo n.º 46
0
def tvmm(pval=None,
         fval=None,
         pmt=None,
         nrate=None,
         nper=None,
         due=0,
         pyr=1,
         noprint=True):
    """Computes present and future values, interest rate and number
    of periods.

    Args:
        pval (float, list): Present value.
        fval (float, list): Future value.
        pmt (float, list): Periodic payment.
        nrate (float, list): Nominal rate per year.
        nper (int, list): Number of compounding periods.
        due (int): When payments are due.
        pyr (int, list): number of periods per year.
        noprint (bool): prints enhanced output


    Returns:
        Argument set to None in the function call.

    Effective interest rate per period is calculated as `nrate` / `pyr`.


    >>> tvmm(pval=5000, nrate=11.32, nper=48, fval=0, pyr=12, noprint=False) # doctest: +ELLIPSIS
    Present Value: .......  5000.00
    Future Value: ........     0.00
    Payment: .............  -130.01
    Due: .................      END
    No. of Periods: ......    48.00
    Compoundings per Year:    12
    Nominal Rate: .......     11.32
    Effective Rate: .....     11.93
    Periodic Rate: ......      0.94

    >>> tvmm(pval=[5, 500, 5], nrate=11.32, nper=48, fval=0, pyr=12, noprint=False) # doctest: +ELLIPSIS
    #   pval   fval    pmt   nper  nrate  erate  prate due
    ------------------------------------------------------
    0   5.00   0.00  -0.13  48.00  11.32  11.93   0.94 END
    1 500.00   0.00  -0.13  48.00  11.32  11.93   0.94 END
    2   5.00   0.00  -0.13  48.00  11.32  11.93   0.94 END
    """

    #pylint: disable=too-many-arguments
    #pylint: disable=too-many-branches

    numnone = 0
    numnone += 1 if pval is None else 0
    numnone += 1 if fval is None else 0
    numnone += 1 if nper is None else 0
    numnone += 1 if pmt is None else 0
    numnone += 1 if nrate is None else 0

    if numnone > 1:
        raise ValueError('One of the params must be set to None')

    if numnone == 0:
        pmt = None

    if pmt == 0.0:
        pmt = 0.0000001

    nrate = numpy.array(nrate)

    if pval is None:
        result = numpy.pv(rate=nrate / 100 / pyr,
                          nper=nper,
                          fv=fval,
                          pmt=pmt,
                          when=due)
    elif fval is None:
        result = numpy.fv(rate=nrate / 100 / pyr,
                          nper=nper,
                          pv=pval,
                          pmt=pmt,
                          when=due)
    elif nper is None:
        result = numpy.nper(rate=nrate / 100 / pyr,
                            pv=pval,
                            fv=fval,
                            pmt=pmt,
                            when=due)
    elif pmt is None:
        result = numpy.pmt(rate=nrate / 100 / pyr,
                           nper=nper,
                           pv=pval,
                           fv=fval,
                           when=due)
    else:
        result = numpy.rate(pv=pval, nper=nper, fv=fval, pmt=pmt,
                            when=due) * 100 * pyr

    if noprint is True:
        if isinstance(result, numpy.ndarray):
            return result.tolist()
        return result

    nrate = nrate.tolist()

    if pval is None:
        pval = result
    elif fval is None:
        fval = result
    elif nper is None:
        nper = result
    elif pmt is None:
        pmt = result
    else:
        nrate = result

    params = vars2list([pval, fval, nper, pmt, nrate])
    pval = params[0]
    fval = params[1]
    nper = params[2]
    pmt = params[3]
    nrate = params[4]

    # raise ValueError(nrate.__repr__())

    erate, prate = iconv(nrate=nrate, pyr=pyr)

    if len(pval) == 1:
        if pval is not None:
            print('Present Value: ....... {:8.2f}'.format(pval[0]))
        if fval is not None:
            print('Future Value: ........ {:8.2f}'.format(fval[0]))
        if pmt is not None:
            print('Payment: ............. {:8.2f}'.format(pmt[0]))
        if due is not None:
            print('Due: .................      {:s}'.format('END' if due ==
                                                            0 else 'BEG'))
        print('No. of Periods: ...... {:8.2f}'.format(nper[0]))
        print('Compoundings per Year: {:>5d}'.format(pyr))
        print('Nominal Rate: .......  {:8.2f}'.format(nrate[0]))
        print('Effective Rate: .....  {:8.2f}'.format(erate))
        print('Periodic Rate: ......  {:8.2f}'.format(prate))

    else:
        if due == 0:
            sdue = 'END'
            txtpmt = []
            for item, _ in enumerate(pval):
                txtpmt.append(pmt[item][-1])
        else:
            sdue = 'BEG'
            txtpmt = []
            for item, _ in enumerate(pval):
                txtpmt.append(pmt[item][0])

        maxlen = 5
        for value1, value2, value3, value4 in zip(pval, fval, txtpmt, nper):
            maxlen = max(maxlen, len('{:1.2f}'.format(value1)))
            maxlen = max(maxlen, len('{:1.2f}'.format(value2)))
            maxlen = max(maxlen, len('{:1.2f}'.format(value3)))
            maxlen = max(maxlen, len('{:1.2f}'.format(value4)))

        len_aux = len('{:d}'.format(len(pval)))

        fmt_num = ' {:' + '{:d}'.format(maxlen) + '.2f}'
        fmt_num = '{:<' + '{:d}'.format(
            len_aux) + 'd}' + fmt_num * 7 + ' {:3s}'
        # fmt_shr = '{:' + '{:d}'.format(len_aux) + 's}'
        fmt_hdr = ' {:>' + '{:d}'.format(maxlen) + 's}'
        fmt_hdr = '{:' + '{:d}'.format(len_aux) + 's}' + fmt_hdr * 7 + ' due'

        txt = fmt_hdr.format('#', 'pval', 'fval', 'pmt', 'nper', 'nrate',
                             'erate', 'prate')
        print(txt)
        print('-' * len_aux + '-' * maxlen * 7 + '-' * 7 + '----')
        for item, _ in enumerate(pval):
            print(
                fmt_num.format(item, pval[item], fval[item], txtpmt[item],
                               nper[item], nrate[item], erate[item],
                               prate[item], sdue))
Ejemplo n.º 47
0
# 时间点的价值。
# pv函数计算现值(present value),即金融资产当前的价值。
# npv函数返回的是净现值(net present value),即按折现率计算的净现金流之和。
# pmt函数根据本金和利率计算每期需支付的金额。
# irr函数计算内部收益率(internal rate of return)。内部收益率是是净现值为0时的有效利
# 率,不考虑通胀因素。
# mirr函数计算修正后内部收益率(modified internal rate of return),是内部收益率的改进
# 版本。
# nper函数计算定期付款的期数。
# rate函数计算利率(rate of interest)。
print u"终值"
#fv函数参数为利率,参数,每期支付金额,现值
print "Future value",np.fv(0.03/4, 5*4,-10,1000)
print u"现值"
#pv函数参数为利率,参数,每期支付金额,终值
print "Present value",np.pv(0.03/4,5*4,-10,1376.09633204)
#npv参数为利率和一个表示现金流的数组.
cashflows = np.random.randint(100,size=5)
cashflows = np.insert(cashflows,0,-100)
print "Cashflows",cashflows
print "Net present value",np.npv(0.03,cashflows)
print u"内部收益率"
print "Internal rate of return",np.irr([-100, 38, 48,90 ,17,36])

print u"分期付款"
#pmt输入为利率和期数,总价,输出每期钱数
print "Payment",np.pmt(0.10/12,12*30,100000)
#nper参数为贷款利率,固定的月供和贷款额,输出付款期数
print "Number of payments", np.nper(0.10/12,-100,9000)
#rate参数为付款期数,每期付款资金,现值和终值计算利率
print "Interest rate",12*np.rate(167,-100,9000,0)
#%% m-기간 기준단리: FV=PV*(1+r/m*n*m) ==> PV=FV/(1+r/m*n*m)
# 년기준복리: FV=PV*(1+r)**n ==> PV=FV/(1+r)**n
# m-기간 기준복리: FV=PV*(1+r/m)*(n*m) ==> PV=FV/(1+r/m)*(n*m)
# 기존 모듈 이용
import scipy as sp
import numpy as np
help(sp.pv)
help(np.pv)
fv = 1276.2815625000003
r = 0.05
n = 5
m = 1
PV_sp = sp.pv(r, n, 0, fv)  # pv(rate, nper, pmt, fv=0, when='end')
print(PV_sp)
PV_np = np.pv(r, n, 0, fv)
print(PV_np)

#%%[과제 43-2] 이자가 6개월에 한번 복리로 계산되고 년이자율이 5%인 계좌의 5년 후1000원의 현재가치는 얼마인가?
#i) 사용자 정의 함수를 사용하여 계산하여 보세요.
import numpy as np
FV = 1000
r = 0.05
n = 5
m = 2


def get_pv(Fv, r, n, m):
    return FV / (1 + r / m * n * m)

Ejemplo n.º 49
0
 def calculate_previous_balance(loan):
     return np.pv((loan.rate/100)/loan.period, loan.period, -loan.payment, -loan.present_balance)
def get_pv_np(Fv, r, n, m):
    return np.pv(r / m, n * m, 0, Fv)
Ejemplo n.º 51
0
    def test_decimal_with_when(self):
        """Test that decimals are still supported if the when argument is passed"""
        # begin
        assert_equal(np.rate(Decimal('10'), Decimal('20'), Decimal('-3500'), Decimal('10000'), Decimal('1')),
                     np.rate(Decimal('10'), Decimal('20'), Decimal('-3500'), Decimal('10000'), 'begin'))
        # end
        assert_equal(np.rate(Decimal('10'), Decimal('20'), Decimal('-3500'), Decimal('10000')),
                     np.rate(Decimal('10'), Decimal('20'), Decimal('-3500'), Decimal('10000'), 'end'))
        assert_equal(np.rate(Decimal('10'), Decimal('20'), Decimal('-3500'), Decimal('10000'), Decimal('0')),
                     np.rate(Decimal('10'), Decimal('20'), Decimal('-3500'), Decimal('10000'), 'end'))

        # begin
        assert_equal(np.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'), Decimal('0'), Decimal('1')),
                     np.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'), Decimal('0'), 'begin'))
        # end
        assert_equal(np.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'), Decimal('0')),
                     np.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'), Decimal('0'), 'end'))
        assert_equal(np.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'), Decimal('0'), Decimal('0')),
                     np.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'), Decimal('0'), 'end'))

        # begin
        assert_equal(np.fv(Decimal('0.075'), Decimal('20'), Decimal('-2000'), Decimal('0'), Decimal('1')),
                     np.fv(Decimal('0.075'), Decimal('20'), Decimal('-2000'), Decimal('0'), 'begin'))
        # end
        assert_equal(np.fv(Decimal('0.075'), Decimal('20'), Decimal('-2000'), Decimal('0')),
                     np.fv(Decimal('0.075'), Decimal('20'), Decimal('-2000'), Decimal('0'), 'end'))
        assert_equal(np.fv(Decimal('0.075'), Decimal('20'), Decimal('-2000'), Decimal('0'), Decimal('0')),
                     np.fv(Decimal('0.075'), Decimal('20'), Decimal('-2000'), Decimal('0'), 'end'))

        # begin
        assert_equal(np.pmt(Decimal('0.08') / Decimal('12'), Decimal('5') * Decimal('12'), Decimal('15000.'),
                            Decimal('0'), Decimal('1')),
                     np.pmt(Decimal('0.08') / Decimal('12'), Decimal('5') * Decimal('12'), Decimal('15000.'),
                            Decimal('0'), 'begin'))
        # end
        assert_equal(np.pmt(Decimal('0.08') / Decimal('12'), Decimal('5') * Decimal('12'), Decimal('15000.'),
                            Decimal('0')),
                     np.pmt(Decimal('0.08') / Decimal('12'), Decimal('5') * Decimal('12'), Decimal('15000.'),
                            Decimal('0'), 'end'))
        assert_equal(np.pmt(Decimal('0.08') / Decimal('12'), Decimal('5') * Decimal('12'), Decimal('15000.'),
                            Decimal('0'), Decimal('0')),
                     np.pmt(Decimal('0.08') / Decimal('12'), Decimal('5') * Decimal('12'), Decimal('15000.'),
                            Decimal('0'), 'end'))

        # begin
        assert_equal(np.ppmt(Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('60'), Decimal('55000'),
                             Decimal('0'), Decimal('1')),
                     np.ppmt(Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('60'), Decimal('55000'),
                             Decimal('0'), 'begin'))
        # end
        assert_equal(np.ppmt(Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('60'), Decimal('55000'),
                             Decimal('0')),
                     np.ppmt(Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('60'), Decimal('55000'),
                             Decimal('0'), 'end'))
        assert_equal(np.ppmt(Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('60'), Decimal('55000'),
                             Decimal('0'), Decimal('0')),
                     np.ppmt(Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('60'), Decimal('55000'),
                             Decimal('0'), 'end'))

        # begin
        assert_equal(np.ipmt(Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('24'), Decimal('2000'),
                             Decimal('0'), Decimal('1')).flat[0],
                     np.ipmt(Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('24'), Decimal('2000'),
                             Decimal('0'), 'begin').flat[0])
        # end
        assert_equal(np.ipmt(Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('24'), Decimal('2000'),
                             Decimal('0')).flat[0],
                     np.ipmt(Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('24'), Decimal('2000'),
                             Decimal('0'), 'end').flat[0])
        assert_equal(np.ipmt(Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('24'), Decimal('2000'),
                             Decimal('0'), Decimal('0')).flat[0],
                     np.ipmt(Decimal('0.1') / Decimal('12'), Decimal('1'), Decimal('24'), Decimal('2000'),
                             Decimal('0'), 'end').flat[0])
Ejemplo n.º 52
0
capital=np.zeros((3, 7))
interets=np.zeros((3, 7))

# Hypothèse de mensualité fixe
mensualite=50.0                     

# Hypothèses de taux (source: meilleurstaux.com au 30/06/2014)
mention=('Bon', 'Très bon', 'Excellent')
duree=np.array(([7, 10, 12, 15, 20, 25, 30])) 
taux=np.array(([0.0223, 0.0245, 0.0263, 0.0281, 0.0300, 0.0337, 0.0425],
      [0.0205, 0.0225, 0.0243, 0.0258, 0.0274, 0.0320, 0.0370],
      [0.0175, 0.0196, 0.0216, 0.0240, 0.0267, 0.0283, 0.0335]))
taux_df=pd.DataFrame(taux, index=mention, columns=duree)
           
for i in range(len(mention)):
    for j in range(len(taux[0])):
        capital[i,j]=np.pv(taux[i,j]/12, duree[j]*12, -mensualite)
        interets[i,j]=mensualite*12*duree[j]-capital[i,j]

# Affichage des résultats
for i in range(len(mention)):
    plt.figure('Taux '+ mention[i])
    plt.title('Taux '+ mention[i])
    plt.grid(color="k")
    plt.xlabel('Durée')
    plt.xlim(5, 31)
    plt.ylabel('Montant (EUR)')
    plt.plot(duree, capital[i], 'b', label='Montant financable')
    plt.plot(duree, interets[i], 'r', label='Interets versés')

plt.show()
 def test_pv(self):
     assert_almost_equal(np.pv(0.07,20,12000,0),
                         -127128.17, 2)
Ejemplo n.º 54
0
def present_value(montly_payment,interest_rate=.05,term=30):
	return numpy.pv((interest_rate/12),(term*12),montly_payment) * -1