예제 #1
0
def trancheIRR(size, tranche, tranches, oc, i):
    if i == len(tranches) - 1:
        a = np.array([-size*oc]) 
    else:
        a = np.array([-size*tranche['size']])
    irr = 12*npf.irr(np.append(a, tranche['cash_flows']))
    return irr
 def test_calculate_return_negative_return(self):
     # Test a multi-period with negative return
     test_data = [{
         'date': datetime(2020, 1, 1),
         'total_deposited': 50,
         'current_portfolio_value': 50,
         'transaction_type': 'deposit'
     }, {
         'date': datetime(2020, 3, 1),
         'total_deposited': 50,
         'current_portfolio_value': 30,
         'transaction_type': 'update_portfolio_value'
     }, {
         'date': datetime(2020, 6, 1),
         'total_deposited': 100,
         'current_portfolio_value': 80,
         'transaction_type': 'deposit'
     }, {
         'date': datetime(2020, 1, 3),
         'total_deposited': 100,
         'current_portfolio_value': 30,
         'transaction_type': 'update_portfolio_value'
     }, {
         'date': datetime(2021, 1, 4),
         'total_deposited': 150,
         'current_portfolio_value': 80,
         'transaction_type': 'deposit'
     }]
     self.test_portfolio.portfolio_history = test_data
     actual_output = self.mwr_calculator.calculate_return(
         self.test_portfolio, annualised=False)
     expected_output = round(irr([-50, -50, -50, 80]) * 100, 2)
     self.assertEqual(actual_output, expected_output)
예제 #3
0
    def calculate_irr(self,
                      rated_rpm_array,
                      D_rotor_array,
                      Power_rated_array,
                      hub_height_array,
                      water_depth_array,
                      aep_array,
                      cabling_cost=None):
        '''
        Calculate Internal Rate of Return [%]

        Input:
        rated_rpm_array   [RPM]
        D_rotor_array     [m]
        Power_rated_array [MW]
        hub_height_array  [m]
        aep_array         [kWh]
        water_depth_array [m]
        '''

        self.calculate_expenditures(rated_rpm_array, D_rotor_array,
                                    Power_rated_array, hub_height_array,
                                    aep_array, water_depth_array, cabling_cost)

        self.calculate_cash_flow()

        self.IRR = 100 * npf.irr(self.CWF)  # [%]

        return self.IRR
예제 #4
0
    def get_kpi(self):
        """Module to calculate investment project indicators:
        Cumulative Cash Flow, Net Present Value, Internal Rate of Return,
        Payback Period, Discounted Payback Period, Profitability Index
        for investment decision making.
        """

        def payback_period(ts):
            """Function to calculate PP with for input time-series
            """
            if not (ts[ts.cumsum() > 0].empty | ts[ts.cumsum() < 0].empty):
                final_full_year = ts[ts.cumsum() < 0].index.values.max()
                fractional_yr = - ts.cumsum()[final_full_year] / \
                                  ts[final_full_year + 1]
                pp = (final_full_year + fractional_yr)
                pp = round(pp, 1)
            elif ts[ts.cumsum() < 0].empty:
                pp = 0
            else:
                pp = np.nan
            return pp
        
        profitability_index = lambda ts:round(((ts>0)*(1-ts.cumsum()
                     / ts.cumsum().min())).max(), 1) if ts.min() < 0 else np.inf
        
        irr = lambda dcf: round(npf.irr(dcf)*100, 1) \
                                            if not np.isnan(npf.irr(dcf)) else 0

        # a loop to get kpi values
        for i, (cf, dcf) in enumerate([(self.df['IOC Net Cash Flow ($m)'],
                                        self.df['IOC DCF @ 12% (half-year)']),
                                    (self.df['State Net Cash Flow ($m)'],
                                     self.df['State DCF @ 12% (half-year)']),
                        (self.df[['IOC Net Cash Flow ($m)',
                                  'State Net Cash Flow ($m)']].sum(axis=1),
                         self.df[['IOC DCF @ 12% (half-year)',
                                  'State DCF @ 12% (half-year)']].sum(axis=1))
                                    ]):
            self.kpi.iloc[:,i] = [round(cf.sum(), 1),
                                  round(dcf.sum(), 1),
                                  irr(cf),
                                  payback_period(cf),
                                  payback_period(dcf),
                                  profitability_index(dcf)]
        self.kpi.index.name = 'Parameter'
       
        return self.kpi
예제 #5
0
 def test_npv_irr_congruence(self):
     # IRR is defined as the rate required for the present value of a
     # a series of cashflows to be zero i.e. NPV(IRR(x), x) = 0
     cashflows = numpy.array([-40000, 5000, 8000, 12000, 30000])
     assert_allclose(npf.npv(npf.irr(cashflows), cashflows),
                     0,
                     atol=1e-10,
                     rtol=0)
예제 #6
0
    def get_profit(self,
                   r,
                   starch_price=320.36,
                   ethanol_price=1.48,
                   rp_price=351.05,
                   p_credit=0.0,
                   grain_product_index=1.0,
                   rP_index=1.0,
                   feedstock_index=1.0,
                   chem_index=1.0,
                   utility_index=1.0,
                   tax=0.35):
        '''return net profit as annualized value, $/yr '''
        revenue = self.get_revenue(starch_price=starch_price,
                                   ethanol_price=ethanol_price,
                                   p_credit=p_credit,
                                   rp_price=rp_price,
                                   grain_product_index=grain_product_index,
                                   rP_index=rP_index)[-1]
        cost = self.get_cost(feedstock_index=feedstock_index,
                             chem_index=chem_index,
                             utility_index=utility_index)[-1]
        taxable_income = revenue - cost
        net_profit = taxable_income * (1 - tax)  # assume 40% as default tax

        if self.tech_GP == 1:
            direct_fixed_cost = self.df[self.column][12]  # $/yr
            # depreciation_cost = self.df[self.column][16]  # $/yr
            depreciation_cost = direct_fixed_cost * 0.0655  # $/yr
        elif self.tech_GP == 2:
            direct_fixed_cost = self.df[self.column][12] + self.df[
                self.column][34]  # $/yr
            # depreciation_cost = self.df[self.column][16] + self.df[self.column][38]  # $/yr
            depreciation_cost = direct_fixed_cost * 0.0655  # $/yr
        working_capital = direct_fixed_cost * 0.05  # assume 5%
        cash_flow_list = [
            -(direct_fixed_cost * tax + working_capital),
            -(direct_fixed_cost * (1 - tax))
        ]
        for i in depreciation_rate:
            cash_flow_i = (revenue-(cost-depreciation_cost) - \
                           direct_fixed_cost*i)*(1-tax) + direct_fixed_cost*i
            cash_flow_list.append(cash_flow_i)
        npv = npf.npv(r, cash_flow_list)
        irr = npf.irr(cash_flow_list)
        annualized_value = npv / annuity_factor(20, r)
        a = [cost, revenue, taxable_income, net_profit]
        b = [
            direct_fixed_cost, working_capital, depreciation_cost,
            cash_flow_list
        ]
        return a, b, irr, npv, annualized_value


# wet_1 = Grain(plant_type=1, plant_capacity=5.0, tech_GP=2)
# (Grain(plant_type=1, plant_capacity=2.1, tech_GP=2).get_energy_use()[-1] + \
#     Grain(plant_type=1, plant_capacity=5.0, tech_GP=2).get_energy_use()[-1] + \
#         Grain(plant_type=2, plant_capacity=120, tech_GP=2).get_energy_use()[-1])/(10**6)
def oekonomie_berechnen_gw_ve(leistung_pv, eco, kW, kalkulatorischer_zins,
                              einspeiseverguetung_vektor):
    # Imports
    import numpy as np
    import numpy_financial as npf
    import copy
    # Berechnung
    kalkulatorischer_zins /= 100

    summe_e_pv2g = np.sum(leistung_pv) / (60 * 1000)

    # Erloese aus den Energieflüssen
    einspeiseverguetung = (np.minimum(10, kW) / kW * (einspeiseverguetung_vektor[0]/100) \
        + np.minimum(30, kW - np.minimum(10, kW)) / kW * (einspeiseverguetung_vektor[1]/100) \
        + np.minimum(60, kW - np.minimum(30, kW - np.minimum(10, kW)
                                         ) - np.minimum(10, kW)) / kW * (einspeiseverguetung_vektor[2]/100))
    ersparnis_pv2g = summe_e_pv2g * einspeiseverguetung

    # Gewinn 20 Jahre
    gewinn_pv_20 = np.zeros(20)
    gewinnkurve = np.zeros(21)
    gewinnkurve[0] = np.round(-1 * eco["invest"], 0)

    stromgestehung_zaehler = np.zeros(20)
    stromgestehung_nenner = np.zeros(20)

    for n in range(20):
        if n > 0:
            eco["betrieb"] += eco["betrieb"] * kalkulatorischer_zins
        gewinn_pv_20[n] = ersparnis_pv2g - eco["betrieb"]
        gewinnkurve[n + 1] = gewinnkurve[n] + gewinn_pv_20[n]

        #Stromgestehungskosten Zaehler und Nenner
        if n == 0:
            stromgestehung_zaehler[n] = (eco["invest"] + eco["betrieb"]) / (
                (1 + kalkulatorischer_zins)**n)
        stromgestehung_nenner[n] = summe_e_pv2g / (
            (1 + kalkulatorischer_zins)**n)

    gewinn_nettobarwert = np.concatenate([[gewinnkurve[0]], gewinn_pv_20])
    nettobarwert = np.round(
        npf.npv(kalkulatorischer_zins, gewinn_nettobarwert), 0)

    if kW == 0:
        rendite = 0
        nettobarwert = 0
    else:
        rendite = np.round(
            npf.irr(np.concatenate([[gewinnkurve[0]], gewinn_pv_20])), 2)
        rendite *= 100

    #Stromgestehungskosten
    zaehler = np.sum(stromgestehung_zaehler)
    nenner = np.sum(stromgestehung_nenner)
    stromgestehungskosten = np.round((zaehler / nenner) * 100, 1)

    return nettobarwert, rendite, gewinnkurve, stromgestehungskosten
예제 #8
0
파일: tranche.py 프로젝트: ands3/ABS-Pricer
 def IRR(cls, notional, totalPmts):
     '''
     Return the annualized internal rate of return (IRR).
     '''
     logging.debug(f'IRR() class method takes the tranche notional of {notional} and all periodic payments, both '
                   f'interest and principal, made to the tranche of {totalPmts} and uses those to compute IRR via '
                   'npf.irr(). The resulting number is then annualized to get the annualized Internal Rate of '
                   'Return.')
     return npf.irr([-notional] + totalPmts) * 12
예제 #9
0
 def build_sensitivity_results(self, results_df):
     for index, row in results_df.iterrows():
         processed_cashflows = self.build_cashflows(row["R_AdjustFact"], row["E_AdjustFact"], row["FCI_AdjustFact"])
         cashflow_arr = np.array(processed_cashflows[Cash_flow])
         NPV = round(np_fi.npv(self.i, cashflow_arr), 2)
         IRR = round(np_fi.irr(cashflow_arr), 4)
         results_df.loc[index, 'NPV'] = NPV
         results_df.loc[index, 'IRR'] = IRR
     return results_df
예제 #10
0
def IRR(values: xltypes.XlArray,
        guess: xltypes.XlNumber = None) -> xltypes.XlNumber:
    """Returns the internal rate of return for a series of cash flows

    https://support.office.com/en-us/article/
        irr-function-64925eaa-9988-495b-b290-3ad0c163c1bc
    """
    # `guess` is not used, but unnecessary, since it is a pure perforamnce
    # optimization.
    return numpy_financial.irr(xl.flatten(values))
예제 #11
0
파일: CBA.py 프로젝트: epri-dev/DER-VET
    def internal_rate_of_return(proforma):
        """ calculates the discount rate that would return lifetime NPV= 0

        Args:
            proforma (DataFrame): Pro-forma DataFrame that was created from each ValueStream or DER active

        Returns: internal rate of return

        """
        return npf.irr(proforma['Yearly Net Value'].values)
 def IRR(self):
     period = self.totalPaymentPeriod(
     )  # Override method from StandardTranche
     # Override method from StandardTranche to find CF per period
     cf = [self.paymentPerPeriod(t) for t in range(1, period)]
     cf.insert(
         0,
         (-self.notional))  # insert original notional value as cash outflow
     self.r = numpy_financial.irr(cf) * 12  # Return annualized IRR
     return self.r
예제 #13
0
def IRR(values: xl.Range, guess: xl.Number = None):
    """Returns the internal rate of return for a series of cash flows

    https://support.office.com/en-us/article/
        irr-function-64925eaa-9988-495b-b290-3ad0c163c1bc
    """
    if guess is not None and guess != 0:
        raise NotImplementedError(
            '"guess" value for IRR() is {guess} and not 0')

    return numpy_financial.irr(xl.flatten(values))
예제 #14
0
def calculate_yields(df):
    yields = []
    df['date'] = df['date'].astype('datetime64[ns]')
    df['MaturityDate'] = df['MaturityDate'].astype('datetime64[ns]')
    for row in df.itertuples():
        num_coupons, price, rate = row.NumCoupons, row.pClose, row.CouponRate
        # dirty_price = (row.DaysSince*rate/365) + price
        yield_rate = npf.irr(cash_flows(num_coupons, price, rate))
        yields.append(yield_rate * 2)
    df["Yields"] = pd.Series(yields)
    return df
예제 #15
0
def xirr(values, guess=0.1):
    with np.errstate(divide='ignore', invalid='ignore'):
        import numpy_financial as npf
        res = npf.irr(tuple(flatten(text2num(replace_empty(values)).ravel())))
        res = (not np.isfinite(res)) and Error.errors['#NUM!'] or res

        def _(g):
            e = isinstance(g, str) and Error.errors['#VALUE!']
            return get_error(g, e) or res

        guess = text2num(replace_empty(guess))
        return np.vectorize(_, otypes=[object])(guess).view(Array)
예제 #16
0
def main():
    outpath = Path("~/drop20/")
    outpath.mkdir(parents="True", exist_ok="True")
    print("create the simulations")
    tcf, cfl, aql = at.main()
    irr = npf.irr(tcf.values)
    irr = (1.0 + irr)**12 - 1.0
    print(f"irr={irr:.4f}")
    print("visualize")
    porta = PortfolioAnalysis(fund_assets=100000000,
                              acq_list=aql,
                              outpath=outpath)
    porta.visualize()
예제 #17
0
 def test_gh_39(self):
     cashflows = numpy.array([
         -217500.0, -217500.0, 108466.80462450592, 101129.96439328062,
         93793.12416205535, 86456.28393083003, 79119.44369960476,
         71782.60346837944, 64445.76323715414, 57108.92300592884,
         49772.08277470355, 42435.24254347826, 35098.40231225296,
         27761.56208102766, 20424.721849802358, 13087.88161857707,
         5751.041387351768, -1585.7988438735192, -8922.639075098821,
         -16259.479306324123, -23596.31953754941, -30933.159768774713,
         -38270.0, -45606.8402312253, -52943.680462450604,
         -60280.520693675906, -67617.36092490121
     ])
     assert_almost_equal(npf.irr(cashflows), 0.12)
예제 #18
0
    def presentValue(self):
        # presentValue = (self.cashflow/((1 + self.discount) ** self.year))
        # print(self.year,"년에 대한" ,"현재 자산가지 :", presentValue)
        # 1. 세부 지표 값 구하기
        loss = [-750, -250]
        profit = [100] * 18
        cf = loss + profit
        cashflow = np.array(cf)

        # 2. 순현재가치(NPV)와 내부수익률(IRR) 구하기
        npv = npf.npv(0.045, cashflow)
        irr = npf.irr(cashflow)

        print("순현재가치(npv) : ", npv, "내부수익률(irr) : ", irr)
예제 #19
0
    def compute_rates(self):
        """Compute rates for cash flow analysis

        Study Period = Life(yrs) * Repetitions
        NPW = Factor * Amount
        Factor = E_Factor{_Inv}(MARR, Type, Start, End, Param/Salvage)
            {_Inv} if investment, different function otherwise
        Present (Life) = Sum(All NPW)
        Uniform (Life) = -PMT(MARR, Life(yrs), 1) * Present(Life)
        Present (SP) = -PV(MARR, Study Period, 1) * Uniform(Life)
        IRR - Algorithm...
        """
        self.study_period = float(self.life.get()) * float(self.reps.get())

        # NPW & Factor Calcs
        self.invest_factors, self.invest_npws = 0, 0
        if self.num_invest > 0:
            self.invest_factors = [1 for _ in range(self.num_invest)]
            self.invest_npws = [
                float(x.get()) for x in self.invest_amount_ents
            ]
        self.flow_factors, self.flow_npws = 0, 0
        self.marr = float(self.rate_percent.get()) / 100
        if self.num_flows > 0:
            self.flow_factors = [
                1 / ((1 + self.marr)**(float(start.get())))
                for start in self.flow_start_ents
            ]
            self.flow_npws = [
                factor * float(amount.get()) for factor, amount in zip(
                    self.flow_factors, self.flow_amount_ents)
            ]

        # present/uniform lifes & present sp
        self.present_life = sum(self.invest_npws) + sum(self.flow_npws)
        #self.uniform_life =
        #self.present_sp =
        # Calculate Internal rate of return
        net_cash_flows = [0] * (self.num_flows + self.num_invest)
        for i in range(self.num_invest):
            start = int(self.invest_start_ents[i].get())
            amount = float(self.invest_amount_ents[i].get())
            net_cash_flows[start] += amount
        for f in range(self.num_flows):
            start = int(self.flow_start_ents[f].get())
            amount = float(self.flow_amount_ents[f].get())
            net_cash_flows[start] += amount
        self.irr = npf.irr(net_cash_flows)
        self.place_rates()
예제 #20
0
    def get_irr_return(self):
        order_tmp = self.order.copy()
        portfolio_value = self.get_portfolio_value()
        cash_expense = self.get_cash_expense()
        irr_list = []
        irr_return = []
        for idx, val in enumerate(list(portfolio_value['portfolio_value'])):
            money = cash_expense['cash_expense'][idx]
            irr_list.append(-money)
            return_measure = npf.irr(irr_list[:-1] + [irr_list[-1] + val])
            irr_return.append(return_measure)

        self.irr_return = pd.DataFrame(irr_return,
                                       index=order_tmp.index,
                                       columns=['irr_return'])

        return self.irr_return
예제 #21
0
    def calculate_return(self,
                         portfolio: InvestmentPortfolio,
                         annualised: bool = True) -> Any:
        """
        Calculate the money-weighted rate of return of the portfolio.

        Parameters
        ----------
        portfolio : InvestmentPortfolio
            The portfolio we are calculating the money-weighted return for.
        annualised : bool
            If True, calculate the annualised return.

        Returns
        -------
        Any : The money-weighted rate of return of the portfolio, as a percentage.
            e.g. 18 represents 18%.
        """
        # If there isn't enough data in the portfolio, raise an error
        if len(portfolio.portfolio_history) <= 1:
            raise ValueError(
                'Not enough portfolio data to calculate a return.')

        # Otherwise, calculate the money-weighted return
        mwr_arr = []
        df = pd.DataFrame(portfolio.portfolio_history)

        deposits_and_withdrawals_df = df.loc[df['transaction_type'].isin(
            ['deposit', 'withdrawal'])]

        # Get deposit and withdrawal amounts
        total_deposited_diff = deposits_and_withdrawals_df[
            'total_deposited'].diff()

        mwr_arr.append(-df['total_deposited'][0])
        mwr_arr.extend(np.negative(list(total_deposited_diff)[1:]))
        mwr_arr.append(df['current_portfolio_value'].iloc[-1])

        mwr_return_percentage = (irr(mwr_arr)) * 100

        if annualised:
            mwr_return_percentage = self.calculate_annualised_return(
                portfolio, mwr_return_percentage)

        return round(mwr_return_percentage, 2)
예제 #22
0
def compute_irr(df, initial_invest=0):
    irr = 0
    computed_irr = []
    yearly_cash_flow = [
        df['Cash Flow'].iloc[i * 12:i * 12 + 12].sum()
        for i in range(int(len(df) / 12))
    ]

    for i in range(len(yearly_cash_flow)):
        cf = list(yearly_cash_flow[:i])
        cf += [df['Resell value'].iloc[i * 12]]
        cf[0] = cf[0] - initial_invest

        #        if irr == 0 or i % 6 == 0:
        irr = numpy_financial.irr(cf) * 100
        computed_irr += [irr]

    df['IRR'] = [computed_irr[int((i - i % 12) / 12)] for i in range(len(df))]
    return df
    def test_irr(self):
        v = [-150000, 15000, 25000, 35000, 45000, 60000]
        assert_almost_equal(npf.irr(v), 0.0524, 2)
        v = [-100, 0, 0, 74]
        assert_almost_equal(npf.irr(v), -0.0955, 2)
        v = [-100, 39, 59, 55, 20]
        assert_almost_equal(npf.irr(v), 0.28095, 2)
        v = [-100, 100, 0, -7]
        assert_almost_equal(npf.irr(v), -0.0833, 2)
        v = [-100, 100, 0, 7]
        assert_almost_equal(npf.irr(v), 0.06206, 2)
        v = [-5, 10.5, 1, -8, 1]
        assert_almost_equal(npf.irr(v), 0.0886, 2)

        # Test that if there is no solution then npf.irr returns nan
        # Fixes gh-6744
        v = [-1, -2, -3]
        assert_equal(npf.irr(v), numpy.nan)
예제 #24
0
 def test_gh_15(self):
     v = [
         -3000.0,
         2.3926932267015667e-07,
         4.1672087103345505e-16,
         5.3965110036378706e-25,
         5.1962551071806174e-34,
         3.7202955645436402e-43,
         1.9804961711632469e-52,
         7.8393517651814181e-62,
         2.3072565113911438e-71,
         5.0491839233308912e-81,
         8.2159177668499263e-91,
         9.9403244366963527e-101,
         8.942410813633967e-111,
         5.9816122646481191e-121,
         2.9750309031844241e-131,
         1.1002067043497954e-141,
         3.0252876563518021e-152,
         6.1854121948207909e-163,
         9.4032980015353301e-174,
         1.0629218520017728e-184,
         8.9337141847171845e-196,
         5.5830607698467935e-207,
         2.5943122036622652e-218,
         8.9635842466507006e-230,
         2.3027710094332358e-241,
         4.3987510596745562e-253,
         6.2476630372575209e-265,
         6.598046841695288e-277,
         5.1811095266842017e-289,
         3.0250999925830644e-301,
         1.3133070599585015e-313,
     ]
     result = npf.irr(v)
     assert numpy.isfinite(result)
     # Very rough approximation taken from the issue.
     desired = -0.9999999990596069
     assert_allclose(result, desired, rtol=1e-9)
예제 #25
0
def get_npv_irr(mcc, input_estimates=input_estimates,
                psa_parameters_dict=psa_parameters_dict):
    """Function to get NPV and IRR for each Monte Carlo path
    """

    # getting the previously set input parameters
    # global input_estimates, psa_parameters_dict
    res = []
    # make a copy for further adjustment
    for mc in mcc:
        psa_parameters_dict_mc = psa_parameters_dict.copy()
        input_estimates_mc = input_estimates.copy()

        # set the MC path values according to input 2D array
        psa_parameters_dict_mc['Oil Price ($/bbl)'] *= mc[0, 0]
        input_estimates_mc *= mc[:, :3]

        psa = PSAFinModel(prod_cap_op_cost=input_estimates_mc,
                          parameters_dict=psa_parameters_dict_mc)
        psa.get_ncf()
        res.append([psa.df['IOC DCF @ 12% (half-year)'].sum(),
            npf.irr(psa.df['IOC Net Cash Flow ($m)'])*100])
    return res
예제 #26
0
파일: excellib.py 프로젝트: vmarunov/koala
def irr(values, guess = None):
    """
    Function to calculate the internal rate of return (IRR) using payments and periodic dates. It resembles the
    excel function IRR().

    Excel reference: https://support.office.com/en-us/article/IRR-function-64925eaa-9988-495b-b290-3ad0c163c1bc

    :param values: the payments of which at least one has to be negative.
    :param guess: an initial guess which is required by Excel but isn't used by this function.
    :return: a float being the IRR.
    """
    if isinstance(values, Range):
        values = values.values

    if is_not_number_input(values):
        return numeric_error(values, 'values')

    if guess is not None and guess != 0:
        raise ValueError('guess value for excellib.irr() is %s and not 0' % guess)
    else:
        try:
            return npf.irr(values)
        except Exception as e:
            return ExcelError('#NUM!', e)
예제 #27
0
 def financial_metrics(self, discount_rate):
     return irr(self.df.loc['Cash Flow']), npv(discount_rate,
                                               self.df.loc['Cash Flow'])
예제 #28
0
# Create a numpy array of cash flows for Project 1
cf_project_1 = np.array([-1000, 200, 250, 300, 350, 400, 450, 500, 550, 600])

# Create a numpy array of cash flows for Project 2
cf_project_2 = np.array([-1000, 150, 225, 300, 375, 425, 500, 575, 600, 625])

# Scale the original objects by 1000x
cf_project1 = cf_project_1 * 1000
cf_project2 = cf_project_2 * 1000

import numpy as np
import numpy_financial as npf

# Calculate the internal rate of return for Project 1
irr_project1 = npf.irr(cf_project1)
print("Project 1 IRR: " + str(round(100 * irr_project1, 2)) + "%")

# Calculate the internal rate of return for Project 2
irr_project2 = npf.irr(cf_project2)
print("Project 2 IRR: " + str(round(100 * irr_project2, 2)) + "%")

# Set the market value of debt
mval_debt = 1000000

# Set the market value of equity
mval_equity = 1000000

# Compute the total market value of your company's financing
mval_total = mval_debt + mval_equity
예제 #29
0
def calc_irr(cashflows):
    # Taxa interna de retorno
    return npf.irr(cashflows)
def oekonomie_berechnen_ms(leistung_pv, leistung_last, eco, kW,
                           mieterstrom_zuschlag, kalkulatorischer_zins,
                           betreiber, einspeiseverguetung_vektor):
    # Imports
    import numpy as np
    import numpy_financial as npf

    # Variablen statt festen Werten
    dt_min = 60  # Zeitschrittweite in Minuten

    # Berechnung
    kalkulatorischer_zins /= 100  # Prozent in dezimal

    e_pv2l = np.minimum(leistung_pv, leistung_last)  # in Watt!
    e_pv2g = leistung_pv - e_pv2l  # in Watt!
    # Grid to load
    e_g2l = leistung_last - leistung_pv  # in Watt!
    e_g2l[e_g2l <= 0] = 0  # in Watt!

    # Energiesummen
    summe_e_g2l = np.sum(e_g2l) / (dt_min * 1000
                                   )  # Wattminuten in kWh umgerechnet
    summe_e_pv2l = np.sum(e_pv2l) / (dt_min * 1000)  # in kWh
    summe_e_pv2g = np.sum(e_pv2g) / (dt_min * 1000)  # in kWh
    summe_pvs = np.sum(leistung_pv) / (dt_min * 1000)  # in kWh
    summe_last = np.sum(leistung_last) / (dt_min * 1000)  # in kWh

    # Eigenverbrauchsanteil
    Eigenverbrauchsanteil = np.round((summe_e_pv2l / summe_pvs) * 100, 1)
    # Autarkiegrad
    Autarkiegrad = np.round((summe_e_pv2l / summe_last) * 100, 1)

    # Erloese aus den Energieflüssen
    einspeiseverguetung = (np.minimum(10, kW) / kW * (einspeiseverguetung_vektor[0]/100) \
        + np.minimum(30, kW - np.minimum(10, kW)) / kW * (einspeiseverguetung_vektor[1]/100) \
        + np.minimum(60, kW - np.minimum(30, kW - np.minimum(10, kW)
                                         ) - np.minimum(10, kW)) / kW * (einspeiseverguetung_vektor[2]/100))
    einspeiseverguetung -= 0.004  # Marktprämie abziehen
    ersparnis_pv2g = summe_e_pv2g * einspeiseverguetung

    # Gewinn 20 Jahre
    gewinn_pv_20 = np.zeros(20)
    gewinnkurve = np.zeros(21)
    gewinnkurve[0] = np.round(-1 * eco["invest"], 0)

    # Mieterstromzuschlag
    if mieterstrom_zuschlag == 'Ja':
        if kW < 40:  # Zuschlag berechnen nach: für erste 40kW -8,5 ct, für danach nur -8,0 ct bis 750 kW
            c_mieterstromzuschlag = summe_e_pv2l * \
                np.maximum((einspeiseverguetung - 0.085),0)
        else:
            c_mieterstromzuschlag = summe_e_pv2l * \
                np.maximum((einspeiseverguetung - 0.08),0)
    else:
        c_mieterstromzuschlag = 0

    C_Verwaltung = 100 / 1.19  # Euro pro Jahr und Teilnehmer
    # Rolle und die damit verbundenen Kosten
    if betreiber == 'betreiber-0':
        c_pacht = 0
    else:
        c_pacht = kW * 150 / 20

    stromgestehung_zaehler = np.zeros(20)
    stromgestehung_nenner = np.zeros(20)
    # Berechnung über 20 Jahre:
    for n in range(20):

        if n > 0:  # Achtung, hier werden die aus eco_vorbereiten stammenden Werte überschrieben mit Inflation
            eco["betrieb"] += eco["betrieb"] * kalkulatorischer_zins
            eco["grundpreis"] += eco["grundpreis"] * kalkulatorischer_zins

        # Annahme, damit der Mieterstrom vermarktet werden kann.
        c_Mieterstrompreis = 0.9 * eco["strompreis_vektor"][n]

        # Bonusberechnung (nicht in Oekonomie_berechnen_MS_JB): lcoe
        #Stromgestehungskosten Zaehler und Nenner
        if n == 0:
            stromgestehung_zaehler[n] = (eco["invest"] + eco["betrieb"]) / (
                (1 + kalkulatorischer_zins)**n)
        else:
            #! die Betriebskosten muss ich doch auch jährlich abzinsen!
            stromgestehung_zaehler[n] = (eco["betrieb"]) / (
                (1 + kalkulatorischer_zins)**n)
        stromgestehung_nenner[n] = summe_pvs / ((1 + kalkulatorischer_zins)**n)
        # Ende lcoe

        # Zusammenrechnen der Kosten
        kosten_mieterstrom = -1 * summe_e_g2l*1*c_Mieterstrompreis / 1.19 \
            - eco["betrieb"] /1.19 - eco["umlage"][n]*summe_e_pv2l - \
            C_Verwaltung*eco["i_teilnehmer"] - c_pacht
        gewinne_mieterstrom = summe_last*1*c_Mieterstrompreis /1.19 \
            + c_mieterstromzuschlag + ersparnis_pv2g \
            + eco["grundpreis"] * eco["i_teilnehmer"] / 1.19
        # Volleinspeisung vs. MS:
        gewinn_pv_20[n] = np.maximum(summe_pvs * einspeiseverguetung - eco["betrieb"] /1.19,\
            gewinne_mieterstrom + kosten_mieterstrom)  # Mieterstrom
        gewinnkurve[n + 1] = gewinnkurve[n] + gewinn_pv_20[n]  # kumuliert
    # Schleifenende 20 Jahre

    gewinn_nettobarwert = np.concatenate([[gewinnkurve[0]], gewinn_pv_20])
    nettobarwert = np.round(
        npf.npv(kalkulatorischer_zins, gewinn_nettobarwert), 0)

    if kW == 0:  # warum fragen wir das ab?!
        rendite = 0
        nettobarwert = 0
    else:
        rendite = npf.irr(gewinn_nettobarwert)
        rendite = np.round(rendite * 100, 2)

    #BS: soweit OK

    #Stromgestehungskosten
    zaehler = np.sum(stromgestehung_zaehler)
    nenner = np.sum(stromgestehung_nenner)
    stromgestehungskosten = np.round((zaehler / nenner) * 100, 1)

    return nettobarwert, rendite, gewinnkurve, Eigenverbrauchsanteil, Autarkiegrad, stromgestehungskosten