Beispiel #1
0
def Macaulay_Duration(M, r, rate, n, m):
    '''
    计算麦考利久期
    -------------
    Params
    M: -> float 票面金额
    r: -> float 贴现率
    rate: -> float 票面利率
    n: -> int 年份
    m: -> int 每年计息次数    
    
    Returns
    -------
    D1: -> float 麦考利久期(以期数计)
    D2: -> float 麦考利久期(以年计)
    '''
    rate = rate / m
    r = r / m
    n = n * m
    C = rate * M
    PV = -npf.pv(r, n, C, M)

    df = pd.DataFrame(columns=['期数', '现金流', '贴现值', '占价格比率', '与期数乘积'])
    df.loc[:, '期数'] = np.arange(1, n + 1)
    df.loc[:, '现金流'] = np.array([C] * (n - 1) + [M + C])
    df.loc[:,
           '贴现值'] = df.loc[:, '现金流'].values / ((1 + r)**df.loc[:, '期数'].values)
    df.loc[:, '占价格比率'] = df.loc[:, '贴现值'] / PV
    df.loc[:, '与期数乘积'] = df.loc[:, '期数'].values * df.loc[:, '占价格比率']
    D1 = df.loc[:, '与期数乘积'].sum()
    D2 = D1 / m
    return D1, D2
    def discounted_payback_period(self):
        # discount future cash flows at desired return rate
        annual_cash_flow_df = self.annual_cashflow_df.copy()
        annual_cash_flow_df[DISCOUNTED_CASHFLOW] = np_fi.pv(
            self.annual_discount_rate,
            pmt=0,
            nper=annual_cash_flow_df.index,
            fv=-annual_cash_flow_df[CASHFLOW])
        annual_cash_flow_df[CUMULATIVE_CASHFLOW] = np.cumsum(
            annual_cash_flow_df[DISCOUNTED_CASHFLOW])

        # get when the project becomes profitable
        mask_positive = annual_cash_flow_df[CUMULATIVE_CASHFLOW] >= 0
        try:
            min_full_year = annual_cash_flow_df[
                mask_positive].index.values.min() - 1
            profit_point = min_full_year + abs(
                annual_cash_flow_df.loc[min_full_year, CUMULATIVE_CASHFLOW] /
                annual_cash_flow_df.loc[min_full_year + 1,
                                        DISCOUNTED_CASHFLOW])
        except:
            raise Exception("Project not profitable within given time period")

        annual_cash_flow_df.to_csv(
            os.path.join(self.results_path, self.results_file_name))

        return round(profit_point, 2)
Beispiel #3
0
 def calculate_typeB(self, data):
     data['principal_amount'] = npf.pv(self.eair, data['loan_term'],
                                       -data['monthly_amortization'])
     data['sum_payments'] = data['monthly_amortization'] * data['loan_term']
     data['total_interest'] = data['sum_payments'] - \
         data['principal_amount']
     return data
 def get_pres_val(self) -> float:
     return pv(
         self.rate / (100 * self.freq),
         self.freq * self.num_of_years,
         0,
         self.fin_bal,
         self.dep_when,
     )
Beispiel #5
0
def calc_parameter(ask_reply, input_string):
    """ calc_parameter is a calculator to calculate the final goal based on ino given by users.
    
    Parameters
    ---------
    Param1 : Dictionary
        The dictionary stores the float provided by user as value,  stores corresponding terms as the key.
        
    Param2 : String
        The string is the specified goal for caculation. 
        The string implies what the dictionary would be since each value is dependent to the remaining values. 
        
    Returns
    ------
    Return1 : Float
        The final result of requested value after caculation.
    """
    user_fin_dict = ask_reply

    try:
        if (ask_reply['input_string']) == 'present value':
            output = abs(
                npf.pv(user_fin_dict["required rate per year"],
                       user_fin_dict["required time period"],
                       0 - user_fin_dict["payment"],
                       user_fin_dict["future value"]))
        elif (ask_reply['input_string']) == "future value":
            output = abs(
                npf.fv(user_fin_dict["required rate per year"],
                       user_fin_dict["required time period"],
                       0 - user_fin_dict["payment"],
                       0 - user_fin_dict["present value"]))
        elif (ask_reply['input_string']) == "payment":
            output = abs(
                npf.pmt(user_fin_dict["required rate per year"],
                        user_fin_dict["required time period"],
                        0 - user_fin_dict["present value"],
                        user_fin_dict["future value"]))
        elif (ask_reply['input_string']) == "required rate per year":
            output = abs(
                npf.rate(user_fin_dict["required time period"],
                         0 - user_fin_dict["payment"],
                         0 - user_fin_dict["present value"],
                         user_fin_dict["future value"]))
        elif (ask_reply['input_string']) == "required time period":
            output = abs(
                npf.nper(user_fin_dict["required rate per year"],
                         0 - user_fin_dict["payment"],
                         0 - user_fin_dict["present value"],
                         user_fin_dict["future value"]))
        else:
            output = random.choice(unknown_input_reply)
        return output

    except KeyError:
        print("I'm dead because of you !")
        print("You should never have encountered this. What did you do?")
        return None
Beispiel #6
0
def infer_reasonable_share_price(ticker, financialreportingdf, stockpricedf, discountrate, marginrate):
    years = 2  # period
    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('financialreportdf:\n',financialreportingdf)
    try:

        # Calcuate the rate per period
        # parameter:  periods , payment, present value, future value
        firstEPS = financialreportingdf.eps.iloc[0]
        lastEPS = financialreportingdf.eps.iloc[-1]
        # Adjust firstEPS at least 1 , prevent npf.rate get NaN
        if (firstEPS<1):
            adj = 1 - firstEPS
            firstEPS = firstEPS + adj
            lastEPS =  lastEPS + adj
            
        annualgrowthrate = npf.rate(len(financialreportingdf.eps)-1, 0, -1 * firstEPS,lastEPS)
        #print("Annual Growth Rate %f" % annualgrowthrate)

        # Non Conservative
        #print(financialreportingdf)
        lasteps = financialreportingdf.eps.tail(1).values[0]  # presentvalue
        #print('1st eps ',financialreportingdf.eps.iloc[0])
        #print('last eps ',financialreportingdf.eps.iloc[-1])
        #print('annual growth rate ',annualgrowthrate)
        # conservative
        # lasteps = financialreportingdf.eps.mean()

    # np.fv, compute the future value. parameters: interest rate , periods, payment, present value
        futureeps = abs(npf.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'] = findMinimumPER(stockpricedf, financialreportingdf)
    # future stock price
    dfprice['FV'] = dfprice['futureeps'] * dfprice['peratio']
    #print('dfprice:\n',dfprice)
    #print('discountrate: %s' % discountrate)
    dfprice['PV'] = abs(npf.pv(discountrate, years, 0, fv=dfprice['FV']))
    if dfprice['FV'].values[0] > 0:
        dfprice['marginprice'] = dfprice['PV']*(1-marginrate)
    else:
        dfprice['marginprice'] = 0
    dfprice['lastprice'] = stockpricedf.Close.tail(1).values[0]

    dfprice['suggestion'] = np.where(
        (dfprice['lastprice'] < dfprice['marginprice']), 'BUY', 'SELL')
    return dfprice
    def get_ret_fund(self) -> float:
        self.ret_fund = -round(
            pv(
                self.rate / (100 * self.freq),
                self.freq * self.num_of_years,
                self.reg_wdr,
                when=self.wdr_when,
            ),
            2,
        )

        return self.ret_fund
Beispiel #8
0
def PV(
        rate: func_xltypes.XlNumber,
        nper: func_xltypes.XlNumber,
        pmt: func_xltypes.XlNumber,
        fv: func_xltypes.XlNumber = 0,
        type: func_xltypes.XlNumber = 0
) -> func_xltypes.XlNumber:
    """PV, one of the financial functions, calculates the present value of a
    loan or an investment, based on a constant interest rate.

    https://support.office.com/en-us/article/
        pv-function-23879d31-0e02-4321-be01-da16e8168cbd
    """

    return npf.pv(float(rate),
                  float(nper),
                  float(pmt),
                  fv=float(fv),
                  when=int(type))
def generate_decision_1(ticker, financialdf, discountrate, marginrate,
                        stockpriceserie, parameters):
    lasteps = financialdf.EPS.iloc[-1]

    dfprice = pd.DataFrame(columns=['ticker', 'lasteps', 'futureeps'])

    pd.options.display.float_format = '{:20,.2f}'.format
    # print('parameters', parameters)
    annualgrowthrate = float(parameters.annual_growth_rate)
    pe_ratio = float(parameters.pe)
    n_future_year = 5
    try:
        if 1 + annualgrowthrate >= 0:
            futureeps = abs(npf.fv(annualgrowthrate, n_future_year, 0,
                                   lasteps))
        else:
            # This is necessary to catch following condition:
            # 1. Last EPS is negative value
            # 2. 1 + annualgrowthrate < 0
            # Necessary because if (1+annualgrowthrate)^5 will result in - value.
            # And this negative value will negate the negative EPS.
            # Positive result in this value is mathematicaly correct but against
            # a healthy understanding about business logic.
            futureeps = 0
        # print('5.1', [ticker, lasteps, futureeps])
        dfprice.loc[0] = [ticker, lasteps, futureeps]
        # print('5.2')
    except:
        # print('Last EPS:', lasteps)
        # print('Annual Growth Rate:', annualgrowthrate)
        print('EPS does not exist or annual growth rate is missing.')
    dfprice.set_index('ticker', inplace=True)
    dfprice['pe'] = pe_ratio
    dfprice['FV'] = dfprice['futureeps'] * dfprice['pe']
    dfprice['PV'] = npf.pv(discountrate, n_future_year, 0, dfprice['FV']) * -1
    # print(dfprice[['FV', 'PV']])
    dfprice['marginprice'] = np.where((dfprice['futureeps'] > 0),
                                      dfprice['PV'] * (1 - marginrate), 0)
    dfprice['currentshareprice'] = stockpriceserie[-1]
    dfprice['decision'] = np.where(
        (dfprice['currentshareprice'] < dfprice['marginprice']), 'Buy', 'Sell')
    # open_in_excel(dfprice)
    return dfprice
Beispiel #10
0
def bond_pricing(rate, n, M, m):
    '''
    零息债券定价
    -------
    Params
    rate: -> float 贴现率
    n: -> flaot 期限
    M: -> float 票面金额
    m: -> int 每年付息次数
    
    Return
    price: -> float 债券价格
    '''
    # 计算贴现率
    rate = rate / m
    # 计算期数
    n = n * m
    price = npf.pv(rate, n, 0, -M)
    return price
Beispiel #11
0
    def test_when(self):
        # begin
        assert_equal(npf.rate(10, 20, -3500, 10000, 1),
                     npf.rate(10, 20, -3500, 10000, 'begin'))
        # end
        assert_equal(npf.rate(10, 20, -3500, 10000),
                     npf.rate(10, 20, -3500, 10000, 'end'))
        assert_equal(npf.rate(10, 20, -3500, 10000, 0),
                     npf.rate(10, 20, -3500, 10000, 'end'))

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

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

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

        # begin
        assert_equal(npf.nper(0.075, -2000, 0, 100000., 1),
                     npf.nper(0.075, -2000, 0, 100000., 'begin'))
        # end
        assert_equal(npf.nper(0.075, -2000, 0, 100000.),
                     npf.nper(0.075, -2000, 0, 100000., 'end'))
        assert_equal(npf.nper(0.075, -2000, 0, 100000., 0),
                     npf.nper(0.075, -2000, 0, 100000., 'end'))
Beispiel #12
0
    def test_decimal_with_when(self):
        """
        Test that decimals are still supported if the when argument is passed
        """
        # begin
        assert_equal(
            npf.rate(Decimal('10'), Decimal('20'), Decimal('-3500'),
                     Decimal('10000'), Decimal('1')),
            npf.rate(Decimal('10'), Decimal('20'), Decimal('-3500'),
                     Decimal('10000'), 'begin'))
        # end
        assert_equal(
            npf.rate(Decimal('10'), Decimal('20'), Decimal('-3500'),
                     Decimal('10000')),
            npf.rate(Decimal('10'), Decimal('20'), Decimal('-3500'),
                     Decimal('10000'), 'end'))
        assert_equal(
            npf.rate(Decimal('10'), Decimal('20'), Decimal('-3500'),
                     Decimal('10000'), Decimal('0')),
            npf.rate(Decimal('10'), Decimal('20'), Decimal('-3500'),
                     Decimal('10000'), 'end'))

        # begin
        assert_equal(
            npf.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'),
                   Decimal('0'), Decimal('1')),
            npf.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'),
                   Decimal('0'), 'begin'))
        # end
        assert_equal(
            npf.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'),
                   Decimal('0')),
            npf.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'),
                   Decimal('0'), 'end'))
        assert_equal(
            npf.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'),
                   Decimal('0'), Decimal('0')),
            npf.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'),
                   Decimal('0'), 'end'))
Beispiel #13
0
 def get_pv(self):
     return fin.pv(self.rate, self.n, self.pmt, self.fv, self.when)[0]
Beispiel #14
0
def bond_price(face_value, rate, nper):
    return  npf.pv(rate=rate, nper=nper, fv=face_value, pmt=0) * -1
Beispiel #15
0
    print()
    print('*'*50)

while continue_yn=='y':

    if question == 'ask':
        question = input('Do you wish to (M)anually Calculate your PV & FV, or run the (A)ssignment Numbers (M or A)?').upper()

    if question == 'M':
        print()
        cash = float(input('Enter in the Original Price: '))
        rate = float(input("Enter in the Intreset Rate (i.e. 5% is 0.05): "))
        nper = float(input("Enter in the Number of Years: "))
        pmt = float(input("Enter in the Yearly Revenue: "))

        pv = np.pv(rate, nper, pmt, cash)
        fv = np.fv(rate, nper, pmt, pv)

        print('*'*50)
        print(f'Intial Investment:$ {cash}')
        print(f'Intrest Rate: {rate*100}%')
        print(f'Revenue:$ {pmt}')
        print(f'Number of Periods: {nper}')

        investmentGB(pv, fv)
        
        print()
        continue_yn = input('Do you wish to continue? (Y or N)').lower()
        print()

    elif question == 'A':
pmt = -2000
pv = -1000000
fv = npf.fv(rate=rate / 12, nper=nper * 12, pmt=pmt, pv=pv)
#  rate:年化投资回报率
#  nper:投资年数
#  pmt:每月投入资金(负值)
#  pv:期初值(负值)
print(
    f'期初资产¥{abs(pv)}元,每月再投入¥{abs(float(pmt)):.2f}元,年均收益率{rate * 100:.2f}%,{nper}年后期末价值为:¥{abs(fv):.2f}元。'
)
'''pv:计算未来金额在现在的价值'''
rate = 0.035
nper = 20
pmt = -2000
fv = 5000000
pv = npf.pv(rate=rate / 12, nper=nper * 12, pmt=pmt, fv=fv)
#  rate:年化投资回报率
#  nper:投资年数
#  pmt:每月投入资金(负值)
#  fv:预期达到的资产总值(正值)
print(
    f'年均收益率{rate * 100:.2f}%,每月投入¥{abs(float(pmt)):.2f}元,投资{nper}年后,期末资产¥{abs(float(fv)):.2f}元,需要投入本金:¥{abs(pv):.2f}元。'
)
'''pmt:计算每期支付金额'''
rate = 0.075
nper = 20
pv = 1000000
fv = 0
per = 240
pmt = npf.pmt(rate=rate / 12, nper=nper * 12, pv=pv, fv=fv)
#  rate:年化投资回报率
Beispiel #17
0
 def test_pv_decimal(self):
     assert_equal(
         npf.pv(Decimal('0.07'), Decimal('20'), Decimal('12000'),
                Decimal('0')), Decimal('-127128.1709461939327295222005'))
Beispiel #18
0
 def test_pv(self):
     assert_almost_equal(npf.pv(0.07, 20, 12000, 0), -127128.17, 2)
Beispiel #19
0
        final = principal * (1 + rate * n)
    elif interest_type == 'compound':
        final = principal * (1 + rate)**n
    elif interest_type == 'continuous':
        final = principal * np.exp(rate * n)
    else:
        raise Exception('Invalid Type!')
    return final


#%%
# 计算终值
npf.fv(0.1, 4, 0, -1000)

# 计算现值
npf.pv(0.1, 4, 0, -1500)

# 计算净现值
rate, cashflows = 0.08, [-40_000, 5_000, 8_000, 12_000, 30_000]
npf.npv(rate, cashflows).round(5)

#%%
npf.pv(0.06, 3, -100, 0)
npf.pv(0.06, 3, -100, 0, when='begin')

# 验证
npf.pv(0.06, 3, 100, 0, when='begin') / npf.pv(0.06, 3, 100, 0) == 1.06

npf.fv(0.06, 3, -100, 0)
npf.fv(0.06, 3, -100, 0, when='begin')
    def test_decimal_with_when(self):
        """
        Test that decimals are still supported if the when argument is passed
        """
        # begin
        assert_equal(npf.rate(Decimal('10'), Decimal('20'), Decimal('-3500'),
                              Decimal('10000'), Decimal('1')),
                     npf.rate(Decimal('10'), Decimal('20'), Decimal('-3500'),
                              Decimal('10000'), 'begin'))
        # end
        assert_equal(npf.rate(Decimal('10'), Decimal('20'), Decimal('-3500'),
                              Decimal('10000')),
                     npf.rate(Decimal('10'), Decimal('20'), Decimal('-3500'),
                              Decimal('10000'), 'end'))
        assert_equal(npf.rate(Decimal('10'), Decimal('20'), Decimal('-3500'),
                              Decimal('10000'), Decimal('0')),
                     npf.rate(Decimal('10'), Decimal('20'), Decimal('-3500'),
                              Decimal('10000'), 'end'))

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

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

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

        # begin
        assert_equal(npf.ipmt(Decimal('0.1') / Decimal('12'), Decimal('1'),
                              Decimal('24'), Decimal('2000'),
                              Decimal('0'), Decimal('1')).flat[0],
                     npf.ipmt(Decimal('0.1') / Decimal('12'), Decimal('1'),
                              Decimal('24'), Decimal('2000'),
                              Decimal('0'), 'begin').flat[0])
        # end
        assert_equal(npf.ipmt(Decimal('0.1') / Decimal('12'), Decimal('1'),
                              Decimal('24'), Decimal('2000'),
                              Decimal('0')).flat[0],
                     npf.ipmt(Decimal('0.1') / Decimal('12'), Decimal('1'),
                              Decimal('24'), Decimal('2000'),
                              Decimal('0'), 'end').flat[0])
        assert_equal(npf.ipmt(Decimal('0.1') / Decimal('12'), Decimal('1'),
                              Decimal('24'), Decimal('2000'),
                              Decimal('0'), Decimal('0')).flat[0],
                     npf.ipmt(Decimal('0.1') / Decimal('12'), Decimal('1'),
                              Decimal('24'), Decimal('2000'),
                              Decimal('0'), 'end').flat[0])
Beispiel #21
0
def do_one_tick_calculation(company):
   ## ?? not working.
   output = json.dumps(company, indent=4, sort_keys=False)
   re_output = re.sub(r'",\s+', '", ', output)
   print(re_output)

   print(f"======= {company['name']} ======")
   rev_growth = do_calc_growth_rate(company["rev_list"])
   print("rev_growth: ", rev_growth)
   grosspft_growth = do_calc_growth_rate(company["grosspft_list"])
   print("grosspft_growth: ", grosspft_growth)
   eps_growth = do_calc_growth_rate(company["eps_list"])
   print("eps_growth: ", eps_growth)
   bvps_growth = do_calc_growth_rate(company["bvps_list"])
   print("bvps_growth: ", bvps_growth)
   fcf_growth = do_calc_growth_rate(company["fcf_list"])
   print("fcs_growth: ", fcf_growth)


   # tencap calculation
   net_income = company["net_income"]
   income_tax = company["income_tax"]
   depreciation = company["depreciation"]
   receivable_chg = company["receivable_chg"]
   payable_chg = company["payable_chg"]
   capexp = company["capexp"]
   sale_property = company["sale_property"]
   share_num = company["share_num"]
   close_price = company["close_price"]

   owner_earnings = net_income + income_tax + depreciation + receivable_chg + \
                    payable_chg + capexp + sale_property

   tencap_price = (owner_earnings*10)/share_num
   tencap_price_fmt = "{:.2f}".format(tencap_price)
   price_ratio = close_price/tencap_price
   price_ratio_fmt = "{:.2f}".format(price_ratio)

   print("===========")
   print(f"{'*close_price: ' :<20} {close_price}")
   print(f"{'*tencap_price:' :<20} {tencap_price_fmt :<10} [ {price_ratio_fmt} ]")

   # pabriDcf

   growth_rate = 0
   growth_rate_name = ""
   if (bvps_growth != 0):
      growth_rate = bvps_growth
      growth_rate_name = "bvps_growth"
   elif (eps_growth != 0):
      growth_rate = eps_growth
      growth_rate_name = "eps_growth"
   elif (grosspft_growth != 0):
      growth_rate = grosspft_growth
      growth_rate_name = "grosspft_growth"
   elif (rev_growth != 0):
      growth_rate = rev_growth
      growth_rate_name = "rev_growth"

   print(f"{'*growth_rate:' :<20} {growth_rate :<10} [{growth_rate_name}] ")
   cash_from_operations = company["cash_from_operations"]
   capexp = company["capexp"]
   sale_property = company["sale_property"]
   total_cash = company["total_cash"]
   total_debt = company["total_debt"] *-1
   share_num = company["share_num"]

   fcf_y0 = cash_from_operations + capexp + sale_property
   discount_rate = 0.1
   fcf_y1 = fcf_y0 * (1 + growth_rate)
   fcf_y2 = fcf_y1 * (1 + growth_rate)
   fcf_y3 = fcf_y2 * (1 + growth_rate)
   fcf_y4 = fcf_y3 * (1 + growth_rate)
   fcf_y5 = fcf_y4 * (1 + growth_rate)
   fcf_y6 = fcf_y5 * (1 + growth_rate)
   fcf_y7 = fcf_y6 * (1 + growth_rate)
   fcf_y8 = fcf_y7 * (1 + growth_rate)
   fcf_y9 = fcf_y8 * (1 + growth_rate)
   fcf_y10 = fcf_y9 * (1 + growth_rate)

   fcf_y1_dcf =  npf.pv(discount_rate, 1, 0, fcf_y1)*-1
   fcf_y2_dcf =  npf.pv(discount_rate, 2, 0, fcf_y2)*-1
   fcf_y3_dcf =  npf.pv(discount_rate, 3, 0, fcf_y3)*-1
   fcf_y4_dcf =  npf.pv(discount_rate, 4, 0, fcf_y4)*-1
   fcf_y5_dcf =  npf.pv(discount_rate, 5, 0, fcf_y5)*-1
   fcf_y6_dcf =  npf.pv(discount_rate, 6, 0, fcf_y6)*-1
   fcf_y7_dcf =  npf.pv(discount_rate, 7, 0, fcf_y7)*-1
   fcf_y8_dcf =  npf.pv(discount_rate, 8, 0, fcf_y8)*-1
   fcf_y9_dcf =  npf.pv(discount_rate, 9, 0, fcf_y9)*-1
   fcf_y10_dcf =  npf.pv(discount_rate, 10, 0, fcf_y10)*-1
   termination_value = fcf_y10_dcf *10
   current_npv = fcf_y1_dcf + fcf_y2_dcf + fcf_y3_dcf + fcf_y4_dcf + fcf_y5_dcf + \
                 fcf_y6_dcf + fcf_y7_dcf + fcf_y8_dcf + fcf_y9_dcf + fcf_y10_dcf + \
                 termination_value+ total_cash + total_debt

   mydbg2(fcf_y1, fcf_y1_dcf)
   mydbg2(fcf_y8, fcf_y8_dcf)
   #print(current_npv)

   intrinsic_value_per_share = current_npv/share_num
   intrinsic_price_ratio = close_price/intrinsic_value_per_share
   intrinsic_price_ratio_fmt = "{:.2f}".format(intrinsic_price_ratio)

   pabridcf_price = intrinsic_value_per_share/2
   pabridcf_price_ratio = close_price/pabridcf_price
   pabridcf_price_ratio_fmt = "{:.2f}".format(pabridcf_price_ratio)

   print(f"{'*pabDcf_price:' :<20} {round(pabridcf_price, 2):<10} [ {pabridcf_price_ratio_fmt} ]")
   print(f"{'==pabIntrinsic:' :<20} {round(intrinsic_value_per_share, 2):<10} [ {intrinsic_price_ratio_fmt} ]" )

   # payback (eight years)
   payback_sum = fcf_y1 + fcf_y2 + fcf_y3 + fcf_y4 + fcf_y5 + \
                 fcf_y6 + fcf_y7 + fcf_y8

   payback_price = payback_sum/share_num
   payback_price_ratio = close_price/payback_price
   payback_price_ratio_fmt = "{:.2f}".format(payback_price_ratio)

   print(f"{'*payback_price:' :<20} {round(payback_price):<10} [ {payback_price_ratio_fmt} ]" )
Beispiel #22
0
import scipy as sp
import numpy_financial as npf

print(npf.pv(0.075,10,50,1000))
#numpy.pv(rate, nper, pmt, fv=0, when='end')
Beispiel #23
0
# Calculate the discount factor
discount_factor = 1 / ((1 + growth_rate)**(growth_periods))
print("Discount factor: " + str(round(discount_factor, 2)))

# Derive the initial value of the investment
initial_investment_again = 100 * (1 + -0.05)**10 * 1 / (1 + -0.05)**10
print("Initial value: " + str(round(initial_investment_again, 2)))

# Import numpy as np
import numpy as np

import numpy_financial as npf

# Calculate investment_1
investment_1 = npf.pv(rate=0.03, nper=15, pmt=0, fv=10000)

# Note that the present value returned is negative, so we multiply the result by -1
print("Investment 1 is worth " + str(round(-investment_1, 2)) +
      " in today's dollars")

# Calculate investment_2
investment_2 = npf.pv(rate=0.05, nper=10, pmt=0, fv=10000)
print("Investment 2 is worth " + str(round(-investment_2, 2)) +
      " in today's dollars")

import numpy_financial as npf

# Calculate investment_1
investment_1 = npf.fv(rate=0.05, nper=15, pmt=0, pv=-10000)
print("Investment 1 will yield a total of $" + str(round(investment_1, 2)) +
Beispiel #24
0
@author: USUARIO
"""

import pandas as pd
import numpy as np
import numpy_financial as npf
import matplotlib.pyplot as plt

#Valor Presente Valor Futuro
i = 0.05
periodos = 10
pagamento = 0
vp = -10000

valor_presente = npf.pv(i, periodos, pagamento, valor_futuro)
valor_presente

valor_futuro = npf.fv(i, periodos, pagamento, vp)
valor_futuro

#Case 1 - Empresa investir em uma nova planta
ativo = 100000000
passivo_oneroso = 40000000
patrimonio_liquido = 60000000
ki = 0.12
ke = 0.17

wacc = ((passivo_oneroso / ativo) * ki) + ((patrimonio_liquido / ativo) * ke)

wacc
Beispiel #25
0
        print(comp_int, " in interest growth")

    def future_value(n, iy, pv):
        future_value = pv * (1 + iy)**n
        print(future_value, " future value of inv")

    def discount_factor(iy, n):
        disc = 1 / (1 + iy)**n
        print(str(round(disc, 5)), ' discount factor')


TVM.compound_int(n=2, iy=.05, pv=100)
TVM.future_value(n=2, iy=.05, pv=100)
TVM.discount_factor(n=2, iy=.05)

inv = npf.pv(rate=.05, nper=10, pmt=0, fv=100000)
investment_2 = npf.fv(rate=.08, nper=10, pmt=0, pv=-100000)
print("Investment 2 will yield a total of $" + str(round(investment_2, 2)) +
      " in 10 years")
print(inv)
# Calculate investment_3
investment_3 = npf.fv(rate=.08, nper=10, pmt=0, pv=-100000)
print("Investment 3 will yield a total of $" + str(round(investment_3, 2)) +
      " in 10 years")

# Calculate investment_3 and adjsut for inflation of 3%
investment_3_discounted = npf.pv(rate=.03, nper=10, pmt=0, fv=investment_3)
print("After adjusting for inflation, investment 3 is worth $" +
      str(round(-investment_3_discounted, 2)) + " in today's dollars")

#Discounting cashflows with NPV
Beispiel #26
0
#VER: https://cmdlinetips.com/2020/02/useful-personal-finance-functions-numpy-financial/
# https://numpy.org/numpy-financial/latest/

import numpy_financial as np
interestRate = 0.02  # Annual interest rate
compoundingFrequency = 2  # Twice an year
futureLumpSum = 100
presentValue = np.pv(interestRate / compoundingFrequency,
                     compoundingFrequency,
                     0,
                     futureLumpSum,
                     when='end')
print("Interest rate:%2.2f" % interestRate)
print("Compounding Frequency:%d" % compoundingFrequency)
print("Future value:%5.2f" % futureLumpSum)
print("Present value:%5.2f" % presentValue)