def get_rate_savings(self): return (rate( self.freq * self.num_of_years, -self.reg_dep, -self.ini_dep, self.fin_bal, self.dep_when, ) * self.freq * 100)
def getGrowthRate(nper, pv, fv): if isinstance(pv, str): pv = float(pv.replace(',', '')) if isinstance(fv, str): fv = float(fv.replace(',', '')) return np.rate(nper - 1, 0, -pv, fv)
def get_rate_loans(self): return (rate( self.freq * self.num_of_years, -self.reg_pmt, self.loan, 0, self.pmt_when, ) * self.freq * 100)
def FuturePricing(ticker, data_table, discount_rate, margin_rate): df = pd.DataFrame.from_dict(data_table) years = 10 margin_price = 0 fv = float(df['Diluted Normalized EPS'].iloc[0]) # last EPS pv = float(df['Diluted Normalized EPS'].iloc[-1]) # first EPS annual_growth_rate = np.rate(5, 0, -pv, fv) future_eps = abs(np.fv(annual_growth_rate, years, 0, pv)) # Finding the P/E Ratio selected_stock_df = dr.DataReader(ticker, data_source='yahoo', start=(dt.now() - relativedelta(years=5)), end=dt.now()) selected_stock_df['year'] = pd.DatetimeIndex(selected_stock_df.index).year gframe = selected_stock_df.groupby('year').head(1).set_index( 'year').iloc[::-1] df.set_index('Year', inplace=True) price_by_year = pd.DataFrame() price_by_year['Close'] = gframe['Close'] price_by_year['EPS'] = df['Diluted Normalized EPS'].astype(float) price_by_year['P/E Ratio'] = price_by_year['Close'] / price_by_year['EPS'] pe_ratio = price_by_year['P/E Ratio'].min() FV = future_eps * pe_ratio PV = abs(np.pv(discount_rate, years, 0, FV)) if FV > 0: margin_price = PV * (1 - margin_rate) last_share_price = selected_stock_df.Close.tail(1).values[0] decision = np.where(last_share_price < margin_price, 'COMPRAR', 'VENDER') answer = [ dict(annual_growth_rate=np.round(annual_growth_rate, 2), last_eps=np.round(fv, 2), future_eps=np.round(future_eps, 2), pe_ratio=np.round(pe_ratio, 2), FV=np.round(FV, 2), PV=np.round(PV, 2), margin_price=np.round(margin_price, 2), last_share_price=np.round(last_share_price, 2), decision=decision) ] return answer
def BONDS2(): r = 0.09 # Coupon rate = 9% par = 1000 # Par value = $1,000 C = r * par # Annual coupon = $90 frequency = 1 t = 14 # Years left to maturity = 14 nper = t * frequency pv = 850.46 # Selling price = $850.46 YTM = (np.rate(nper = nper, pmt = C, pv = pv, fv = par)) print("""Answer 2: The Yield to maturity is: {:,.2f}%\n""".format(YTM*100))
def average_capital_plus_interest_by_actualInterest(PV,mouth_rate,nper): year_actual_Interest=mouth_rate*PV*nper FV=PV+year_actual_Interest PMT=FV/nper EIR=np.rate(nper,-PMT,PV,0)*12 actual_mouth_rate=EIR/12 for i in range(1, nper + 1): PPMT = np.ppmt(actual_mouth_rate, i, nper, PV) IPMT = np.ipmt(actual_mouth_rate, i, nper, PV) yield i,-PPMT,-IPMT,PMT if i == nper: yield year_actual_Interest,round(EIR,4)
def equal_capital_equal_interest(PV,mouth_rate,nper,Sum_interest=0): PPMT = PV / nper IPMT = PV * mouth_rate PMT=PPMT+IPMT EIR = np.rate(nper, -PMT, PV, 0) * 12 for i in range(1, nper + 1): left_capital = PV - PPMT * (i - 1) #求出剩余本金 Sum_interest += IPMT actual_mouth_RATE = IPMT / left_capital yield i,round(left_capital,1),round(PPMT,1), round(IPMT,1), round(PMT,1),round(actual_mouth_RATE,4) if i == nper: yield Sum_interest, round(EIR,4)
def test_rate_nan(self, number_type): # Rate will return NaN, if newton raphson method's change or diff was not able to become # less than default tolerance value i.e. 1e-6 in max iterations possible, rate = np.rate(number_type(12.0), number_type('400.0'), number_type('10000.0'), number_type(0)) assert_equal(np.nan, float(rate)) rate = np.rate(number_type(12.0), number_type('-400.0'), number_type('10000.0'), number_type(20000)) assert_equal(np.nan, float(rate)) # begin rate = np.rate(number_type(12.0), number_type('400.0'), number_type('10000.0'), number_type(20000), 1) assert_equal(np.nan, float(rate)) rate = np.rate(number_type(12.0), number_type('400.0'), number_type('10000.0'), number_type(20000), 'begin') assert_equal(np.nan, float(rate)) # end rate = np.rate(number_type(12.0), number_type('400.0'), number_type('10000.0'), number_type(0)) assert_equal(np.nan, float(rate)) rate = np.rate(number_type(12.0), number_type('400.0'), number_type('10000.0'), number_type(0), 'end') assert_equal(np.nan, float(rate))
def DCF7(): m = 30 # duration of mortgage loan = 30 years n = m * 12 # Because we are considering monthly payments, we need to multiply m by number of months in a year = 360 r = 0.8 # interest rate = 80% TP = 2800000 # Total Price = $2,800,000 MP = TP * r # Mortgage loan price = 80% of Total Price = $2,240,000 P = 17000 # Monthly Payment = $17,000 rate = np.rate(nper=n,pmt=P,pv=MP,fv=0,when='end')*12 APR = rate EAR = ((1 + (APR/12))**(12))-1 print("""Answer 7: a) The APR on this loan is: {0:,.2f}% b) The EAR is: {1:,.2f}%\n""".format(APR*100, EAR*100))
def equal_capital_equal_interest(PV,mouth_rate,nper,Sum_interest=0,returned_capital=0): PPMT = PV / nper IPMT = PV * mouth_rate PMT=PPMT+IPMT EIR = np.rate(nper, -PMT, PV, 0) * 12 for i in range(1, nper + 1): returned_capital += PPMT # 求出已还本金 left_capital = PV - returned_capital # 求出剩余本金 Sum_interest += IPMT actual_mouth_rate = IPMT / (left_capital + PPMT) Sum_money = PV + Sum_interest yield '第'+str(i)+'期',round(PPMT,1), round(IPMT,1), round(PMT,1),round(left_capital,1),"%.2f%%" % (actual_mouth_rate * 100) if i == nper: yield "还款总额:"+str(round(Sum_money,1)),"总利息:"+str(round(Sum_interest,1)),"年利率:"+str("%.2f%%" % (EIR * 100))
def cal_annual_rate_3(first_money, total_years, per_save, time_interval, last_total_money): ''' def rate(nper, pmt, pv, fv, when='end', guess=None, tol=None, maxiter=100): ... 参数 —— 计算利率 nper :期数 pmt :每期的存款/贷款金额 pv :当前的存款/贷款金额 fv :future value ''' result = np.rate(total_years * 12 / time_interval, -per_save, -first_money, last_total_money) print("\n\n{:^70}\n\n".format("定投利率计算器")) print("初期存款为 {},然后每 {} 个月都会存 {} ,那么 {} 年后能拿到 {},则年化利率为 {}%。".format(first_money, time_interval, per_save, total_years, last_total_money, r(result * 12 / time_interval * 100)))
def generate_price_df(ticker, financialreportingdf, stockpricedf, discountrate, marginrate): dfprice = pd.DataFrame( columns=['ticker', 'annualgrowthrate', 'lasteps', 'futureeps']) pd.options.display.float_format = '{:20,.2f}'.format # Find EPS Annual Compounded Growth Rate # annualgrowthrate = financialreportingdf.epsgrowth.mean() #growth rate try: print(financialreportingdf.eps.iloc[0]) print(financialreportingdf.eps.iloc[-1]) annualgrowthrate = np.rate(5, 0, -1 * financialreportingdf.eps.iloc[0], financialreportingdf.eps.iloc[-1]) print(annualgrowthrate) # Non Conservative lasteps = financialreportingdf.eps.tail(1).values[0] #presentvalue # conservative # lasteps = financialreportingdf.eps.mean() years = 10 #period futureeps = abs(np.fv(annualgrowthrate, years, 0, lasteps)) dfprice.loc[0] = [ticker, annualgrowthrate, lasteps, futureeps] except: print('eps does not exist') dfprice.set_index('ticker', inplace=True) #conservative dfprice['peratio'] = findMinimumEPS(stockpricedf, financialreportingdf) dfprice['FV'] = dfprice['futureeps'] * dfprice['peratio'] dfprice['PV'] = abs(np.pv(discountrate, years, 0, fv=dfprice['FV'])) if dfprice['FV'].values[0] > 0: dfprice['marginprice'] = dfprice['PV'] * (1 - marginrate) else: dfprice['marginprice'] = 0 dfprice['lastshareprice'] = stockpricedf.Close.tail(1).values[0] dfprice['decision'] = np.where( (dfprice['lastshareprice'] < dfprice['marginprice']), 'BUY', 'SELL') return dfprice
def npfin_practice(): # pv:年利率3%,按季度付息,每月付10,5年后获取1376.09633204,求现值 val_pv = np.pv(rate=0.03 / 4, nper=4 * 5, pmt=-10, fv=1376.09633204) print('年利率3%,按季度付息,每月付10,5年后获取1376.09633204,现值:\t{:.2f}'.format(-val_pv)) # fv:年利率3%,按季度付息,本金1000,每月付10,求5年后的终值 val_fv = np.fv(rate=0.03 / 4, nper=4 * 5, pmt=-10, pv=-1000) print('年利率3%,按季度付息,本金1000,每月付10,终值:\t{:.2f}'.format(val_fv)) # fvals = [] # for i in range(1, 11): # fvals.append(np.fv(rate=0.03/4, nper=4*i, pmt=-10, pv=-1000)) # plt.plot(fvals, 'bo') # plt.title('年利率3%,按季度付息,本金1000,每月付10,1-10年后的终值') # plt.show() # pmt:年利率1%,贷款1000万,求每月的分期付款 val_pmt = np.pmt(rate=0.01 / 12, nper=12 * 30, pv=10000000) print('年利率1%,贷款1000万,每月的分期付款:\t{:.2f}'.format(-val_pmt)) # nper:年利率10%,贷款9000,每月付款100,求付款期数 val_nper = np.nper(rate=0.10 / 12, pmt=-100, pv=9000) print('年利率10%,贷款9000,每月付款100,付款期数:\t{:.2f}'.format(val_nper)) # irr:现金流[-100, 38, 48, 90, 17, 36],求内部收益率 val_irr = np.irr(values=[-100, 38, 48, 90, 17, 36]) print('现金流[-100, 38, 48, 90, 17, 36],内部收益率:\t{:.0f}%'.format(100 * val_irr)) # mirr:现金流[-100, 38, 48, 90, 17, 36],投资成本3%,现金再投资收益率3%,求修正内部收益率 val_mirr = np.mirr(values=[-100, 38, 48, 90, 17, 36], finance_rate=0.03, reinvest_rate=0.03) print('现金流[-100, 38, 48, 90, 17, 36],投资成本3%,现金再投资收益率3%,求修正内部收益率:\t{:.0f}%'\ .format(100 * val_mirr)) # rate:贷款9000,每月付100,贷款167个月,求利率 val_rate = 12 * np.rate(nper=167, pmt=-100, pv=9000, fv=0) print('贷款9000,每月付100,贷款167个月,利率:\t{:.0f}%'.format(100 * val_rate)) # npv:随机在0-100之间取5个数作为现金流,利率3%,求净现值 cashflows = np.random.randint(100, size=5) cashflows = np.insert(cashflows, 0, -100) print('Cashflows: {}'.format(cashflows)) val_npv = np.npv(rate=0.03, values=cashflows) print('利率3%,上述现金流下,净现值:\t{:.2f}'.format(val_npv))
def get_descriptor(self, data): contract_connection_model = ContractConnection(eth_conn, MODEL_ADDRESS, ABI_PATH) contract_model = contract_connection_model.contract.functions loan_data = data.get("loanData") descriptor = {} descriptor["first_obligation"] = "0" descriptor["total_obligation"] = "0" descriptor["duration"] = "0" descriptor["interest_rate"] = "0" descriptor["punitive_interest_rate"] = "0" descriptor["frequency"] = "0" descriptor["installments"] = "0" if loan_data: contract_model.validate(loan_data).call() first_obligation_amount, first_obligation_time = contract_model.simFirstObligation(loan_data).call() total_obligation = contract_model.simTotalObligation(loan_data).call() duration = contract_model.simDuration(loan_data).call() descriptor["first_obligation"] = str(first_obligation_amount) descriptor["total_obligation"] = str(total_obligation) descriptor["duration"] = str(duration) descriptor["punitive_interest_rate"] = str(contract_model.simPunitiveInterestRate(loan_data).call()) descriptor["frequency"] = str(contract_model.simFrequency(loan_data).call()) descriptor["installments"] = str(contract_model.simInstallments(loan_data).call()) periodic_rate = np.rate( int(descriptor["installments"]), int(descriptor["first_obligation"]), -int(data["amount"]), 0, maxiter=9999999999999 ) annual_rate = float(periodic_rate) * (86400 * 360) / int(descriptor["frequency"]) perc_rate = annual_rate * 100 perc_rate_round = round(perc_rate, 2) descriptor["interest_rate"] = str(perc_rate_round) return descriptor
def annual_interest_rate(self, monthly_payment, requested_loan): """ https://www.vertex42.com/ExcelArticles/amortization-calculation.html The formula for calculating the annual interest rate is shown below. i = n*((r+1)**(p/n)-1) Where: i = annual interest rate n = 1 for annual compound period p = number of payment periods per year r is the function call of np.rate """ annual_rate = float( ((np.rate(12 * self.years, -monthly_payment, requested_loan, 0) + 1)**12 - 1) * 100) return annual_rate
def hpbymonth(financeamount, flat_interest_perannum, tenor): intsallment = round( financeamount * (1 + flat_interest_perannum / 12 * tenor) / tenor, 6) eir_PerYr = np.rate(tenor, intsallment, -financeamount, fv=0) * 12 # 0.1299999999 for i in range(tenor + 1): if i == 0: accuprincpay = round(float(financeamount), 6) payschedule.append( 'Period,PrincPay,IntPay,installment,PrincBalance,Eir') payschedule.append([i, 0, 0, 0, financeamount, eir_PerYr / 12]) else: pp = np.ppmt(eir_PerYr / 12, i, tenor, -financeamount) ip = np.ipmt(eir_PerYr / 12, i, tenor, -financeamount) accuprincpay = round(accuprincpay - pp, 6) payschedule.append( [i, pp, ip * 1, intsallment, accuprincpay, eir_PerYr / 12]) return payschedule
def rate(nper, pmt, pv, fv=0, when=0, guess=0.1, maxiter=100, *args, **kwargs): """ The interest rate needed to pay off the loan in full for a given period of time :param nper: Number of periods :param pmt: Amount paid per period :param pv: Present Value :param fv: Future Value, if not assigned 0 is assumed :param when: 0 or 1. When the payment is made (Default: the payment is made at the end of the period) :param guess: An assumption of what you think the rate should be :param maxiter: maximum number of iterations :return: """ return np.rate(nper=float(nper), pmt=float(pmt), pv=float(pv), fv=float(fv), when=int(when), guess=float(guess), maxiter=int(maxiter))
def generate_price_df(ticker, financialreportingdf, stockpricedf, discountrate, marginrate): dfprice = pd.DataFrame( columns=['ticker', 'annualgrowthrate', 'lasteps', 'futureeps']) pd.options.display.float_format = '{:20,.2f}'.format # Find EPS Annual Compounded Growth Rate # annualgrowthrate = financialreportingdf.epsgrowth.mean() #growth rate print(financialreportingdf.eps.iloc[0]) print(financialreportingdf.eps.iloc[-1]) annualgrowthrate = np.rate(5, 0, -1 * financialreportingdf.eps.iloc[0], financialreportingdf.eps.iloc[-1]) print(annualgrowthrate) # Estimate stock price 10 years from now (Stock Price EPS * Average PE) # Non Conservative lasteps = financialreportingdf.eps.tail(1).values[0] #presentvalue # conservative # lasteps = financialreportingdf.eps.mean() years = 10 #period futureeps = abs(np.fv(annualgrowthrate, years, 0, lasteps)) dfprice.loc[0] = [ticker, annualgrowthrate, lasteps, futureeps] dfprice.set_index('ticker', inplace=True) dfprice['lastshareprice'] = stockpricedf.Close.tail(1).values[0] # Non conservative #dfprice['peratio'] = dfprice['lastshareprice']/dfprice['lasteps'] #conservative dfprice['peratio'] = findMinimumEPS(stockpricedf, financialreportingdf) dfprice['futureshareprice'] = dfprice['futureeps'] * dfprice['peratio'] dfprice['presentshareprice'] = abs( np.pv(discountrate, years, 0, fv=dfprice['futureshareprice'])) dfprice['marginalizedprice'] = dfprice['presentshareprice'] * (1 - marginrate) return dfprice
def should_refinance(self, new_interest, current_n, costs): """ Return wether or not a loan should be refinance based on: -new interest rate -current_n = time lapsed since loan origination -cost = the total cost of originating a new lona (title insurance,etc) """ current_payment = self.payment current_interest = self.interest fv_after_current_n = np.fv(current_interest,current_n,-current_payment,\ self.principal) payment_after_refinancing = np.pmt(new_interest, self.maturity - current_n, -fv_after_current_n) payment_difference = -current_payment - payment_after_refinancing irr = np.rate(self.maturity - current_n, -payment_difference, -costs, 0) if irr > new_interest: return True else: return False
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)
# 净现值 = 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, 1000) print(round(pmt, 2)) # 期数 = np.nper(利率, 每期支付, 现值) # 以1%的年利率从银行贷款1000元,平均每年还pmt元, # 多少年还清? nper = np.nper(0.01, pmt, 1000) print(int(nper)) # 利率 = np.rate(期数, 每期支付, 现值, 终值) # 从银行贷款1000元,平均每年还pmt元,nper年还清, # 年利率多少? rate = np.rate(nper, pmt, 1000, 0) print(round(rate, 2))
def test_rate(self): assert_almost_equal(np.rate(12,-100,1000,100,1,.01), 0.01996455, 3)
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))
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) print u"窗函数" #bartlett函数可以计算巴特利特窗 window = np.bartlett(42) print "bartlett",window #blackman函数返回布莱克曼窗。该函数唯一的参数为输出点的数量。如果数量 #为0或小于0,则返回一个空数组。 window = np.blackman(10) print "blackman",window # hamming函数返回汉明窗。该函数唯一的参数为输出点的数量。如果数量为0或 # 小于0,则返回一个空数组。 window = np.hamming(42) print "hamming",window # kaiser函数返回凯泽窗。该函数的第一个参 # 数为输出点的数量。如果数量为0或小于0,则返回一个空数组。第二个参数为β值。
def test_rate(self): assert_almost_equal(np.rate(48,-50,2000,50,0,0),0.0080529819239056, 16)
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 test_rate(self): assert_almost_equal(np.rate(10,0,-3500,10000), 0.1107, 4)
def test_rate(self): # Note Gnumeric truncates Nper is it is not an integer # OO Does not truncate and uses the fractional part in the calculation # OO behavior assert_almost_equal(np.rate(12.9,-100,1000, 0),.0388, 4)
def calc_yield(nper, pmt, pv, fv): return np.rate(nper, pmt, pv, fv)
def calcYTM(self): self.ytm = 2*np.rate(2*self.mat, 0.5*self.par*self.cr, -1*self.pr, self.par) print "Bond's YTM = %0.2f%%" % (self.ytm*100)
def test_rate(self): # Gnumeric behavior assert_almost_equal(np.rate(12.9,-100,1000, 0),.0292, 4)
def test_decimal_with_when(self): """POJO.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])
def test_rate_decimal(self): rate = np.rate(Decimal('10'), Decimal('0'), Decimal('-3500'), Decimal('10000')) assert_equal(Decimal('0.1106908537142689284704528100'), rate)
* intressimäära ühe perioodi kohta. Parameetrite tüübid on: * nper : skalaar või järjend Perioodide arv * pmt : skalaar või järjend Makse suurus * fv : skalaar või järjend, valikuline Tulevikuväärtus * pv : skalaar või järjend, valikuline Hetkeväärtus * when : string 'begin' või 'end', valikultine Millal makse sooritama peab (alguses või lõpus) Näide 4 Millise aastase intressimäära juures koguneb 10 aasta jooksul 15000€, kui me hoiustame iga kuu 100€? ------------------------------------------------------------------------------ """ print("\nNäide 4\n-------\n") PERIOD = 10*12 # 10 aastat igakuise maksega PAYMENT = -100 # maksame 100€ kuus, '-' tähendab raha väljavoolu PV = 0 # laenu suurus FV = 15000 rate = np.rate(PERIOD, PAYMENT, PV, FV) print("{0}€ kogunemiseks peab aastane intressimäär olema {1:.2f}%." .format(FV, 100*12*rate))
def test_rate(self): # +- .001 # assert_almost_equal(np.rate(12,-100,1000),0.0292285,3) # needs 4 values default should assume fv = 0 assert_almost_equal(np.rate(12,-100,1000,100),0.01623133, 3)
def get_LoanInfo(loan_number): #loan_number = '1213498' server = '10.203.1.105\\alpha' database = 'test_yang' username = '******' password = '******' cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password) query = """ select LoanNum, FstNm, LstNm, IntRate, FICOScore, HmSt, LoanAmt,b.savings,a.AmortTerm from REPORTS_LS_DM.dbo.Secondary as a inner join [lsprodreports].Reports.dbo.vw_Loan_Info as b on a.loanNum = b.loan_number where LoanNum = 'aaaaaaaa' and b.loan_number = 'aaaaaaaa' """ query = query.replace('aaaaaaaa',loan_number) queryResult = sql.read_sql(query, cnxn) queryResult.loc[len(queryResult)] = ["LoanNum","FstNm","LstNm","IntRate","Fico","State","Amt","savings","Term"] if len(queryResult) > 1 : principal = queryResult["LoanAmt"][0] interest_rate = queryResult["IntRate"][0]/100 term = queryResult["AmortTerm"][0] per = np.arange(term) + 1 ipmt = np.ipmt(interest_rate/12, per, term, principal) ppmt = np.ppmt(interest_rate/12, per, term, principal) pmt = np.pmt(interest_rate/12, term, principal) saving = queryResult["savings"][0] PrepaymentStartYear = 3 principal1 = principal ipmt1 = [] ppmt1 = [] pmt1 = [] lastPaymentMonth = 0 for payment in per: index = payment - 1 if payment> PrepaymentStartYear * 12: total_pay = -pmt + saving InterestPayment = principal1 * interest_rate /12 else: total_pay = -pmt InterestPayment = principal1 * interest_rate /12 if total_pay>=principal1: total_pay = principal1 + InterestPayment if lastPaymentMonth==0: lastPaymentMonth = payment PrincipalPayment = total_pay - InterestPayment principal1 = principal1 - PrincipalPayment ipmt1 = np.append(ipmt1,InterestPayment) ppmt1 = np.append(ppmt1,PrincipalPayment) pmt1 = np.append(pmt1,total_pay) total_int_saved ="$"+ str( round(ipmt.sum() *-1 - ipmt1.sum() ,0)).replace(".0","") erate1 = str(round(np.rate (lastPaymentMonth,(principal + ipmt1.sum())/lastPaymentMonth, -principal,0 )*12*100 , 2)) erate2 = str(round(np.rate (term,(principal + ipmt1.sum())/30/12, -principal,0 )*12*100,2)) lastPaymentYear = str(round(lastPaymentMonth/12,1)) lastPaymentMonth = str(lastPaymentMonth) return queryResult,total_int_saved,erate1,erate2,lastPaymentYear,lastPaymentMonth else: return queryResult, '0.0','0.0','0.0','1900','01'
def single_rate(pv, n, rate, fv, pmt): np.rate(n, pmt, pv, fv, when = 'end')
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])
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, 1), np.pmt(0.08 / 12, 5 * 12, 15000., 0, 'begin'), 4) # end assert_almost_equal(np.pmt(0.08 / 12, 5 * 12, 15000., 0), np.pmt(0.08 / 12, 5 * 12, 15000., 0, 'end'), 4) assert_almost_equal(np.pmt(0.08 / 12, 5 * 12, 15000., 0, 0), np.pmt(0.08 / 12, 5 * 12, 15000., 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., 1), np.nper(0.075, -2000, 0, 100000., 'begin'), 4) # end assert_almost_equal(np.nper(0.075, -2000, 0, 100000.), np.nper(0.075, -2000, 0, 100000., 'end'), 4) assert_almost_equal(np.nper(0.075, -2000, 0, 100000., 0), np.nper(0.075, -2000, 0, 100000., 'end'), 4)
def test_rate(self): assert_almost_equal(np.rate(10, 0, -3500, 10000), 0.1107, 4)
import numpy rate = [1, 2, 3] per = 1 pmt = [1, 2] nper = [1, 2, 2] pv = [1, 2, 4] fv = [1, 2, 4] numpy.rate(nper, pmt, pv, fv, when='end', guess=0.1, tol=1e-06, maxiter=100)
print("Question 3:") print(round(FixedIncome.fv(rate=.04 / 12, nper=120, pv=1000000, pmt=14000), 2)) print("Question 4:") print(round(FixedIncome.pvp(rate=.0300, pmt=10, growth=.1200), 2)) print("Question 5:") pmt = 1000 pv = 0 i = 1 while (i <= 30): discount = 1 / ((1 + .0350)**i) if (i == 1): pv += pmt * discount elif (i <= 5): pmt = pmt * 1.1 pv += pmt * discount else: pv += pmt * discount i += 1 print(round(pv, 2)) print("Question 6:") fv_ann = FixedIncome.pv(rate=.0300, nper=25, pmt=10000, fv=0) pv_ann = FixedIncome.pv(rate=.0300, nper=20, pmt=0, fv=fv_ann) print(round(pv_ann, 2)) print("Question 7:") print(2 * np.rate(nper=40, pmt=30, pv=-893.22, fv=1000)) # print(2*FixedIncome.rate(nper=40, pmt=30, present_value=-893.22, future_value=1000))
@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)