Пример #1
0
    def test_to_jsonable(self):
        LOAN1 = Loan("123-45-6789", 12345, 67890, 987)
        LOAN1.loan_status = "New"

        # just making sure this executes, don't need to check that json package works
        encode_me = LOAN1.to_jsonable()
        self.assertTrue(len(encode_me) > 0,"JSON encoding should exist")
Пример #2
0
    def test_status_validation(self):
        LOAN1 = Loan(None, None, None)

        for txt in ("Bad", "FOO", "Invalid", "approved", None):
            LOAN1.loan_status = txt
            with self.assertRaises(InvalidLoanStatusError) as context:
                LOAN1.validate_loan_status()
Пример #3
0
    def test_loan_value_validation(self):
        LOAN1 = Loan(None, None, None)

        for amt in (0, -10, None):
            LOAN1.loan_value = amt
            with self.assertRaises(InvalidLoanValueError) as context:
                LOAN1.validate_loan_value()
Пример #4
0
    def test_property_value_validation(self):
        LOAN1 = Loan(None, None, None)

        for amt in (0, -10, None):
            LOAN1.prop_value = amt
            with self.assertRaises(InvalidPropertyValueError) as context:
                LOAN1.validate_prop_value()
Пример #5
0
def plot(n_click, principal, payment, rate, ext_pay):
    if ext_pay is None:
        loan = Loan.Loan(principal=principal,
                         rate=rate,
                         payment=payment,
                         extra_payment=0)
    else:
        loan = Loan.Loan(principal=principal,
                         rate=rate,
                         payment=payment,
                         extra_payment=ext_pay)

    loan.check_loan_parameters()
    loan.compute_schedule()

    payment_number, applied_ext, applied_principal, applied_interest, end_principal = [], [], [], [], []

    for pay in loan.schedule.values():
        payment_number.append(pay[0])
        applied_ext.append(pay[3])
        applied_principal.append(pay[4])
        applied_interest.append(pay[5])
        end_principal.append(pay[6])

    ind = np.arange(1, len(payment_number) + 1)

    fig = go.Figure(data=[
        go.Bar(name="Principal",
               x=ind,
               y=applied_principal,
               hovertemplate="Principal:%{y:$.2f}",
               marker_color="#92A8D1"),
        go.Bar(name="Extra Payment",
               x=ind,
               y=applied_ext,
               hovertemplate="Extra Payment:%{y:$.2f}",
               marker_color="#8FBC8F"),
        go.Bar(name="Interest",
               x=ind,
               y=applied_interest,
               hovertemplate="Interest:%{y:$.2f}",
               marker_color="#DEB887")
    ])
    fig.update_layout(barmode='stack',
                      yaxis=dict(title='$ USD',
                                 titlefont_size=16,
                                 tickfont_size=14),
                      xaxis=dict(title='Payment Period'))
    fig.update_layout(barmode='stack',
                      yaxis=dict(title='$ USD',
                                 titlefont_size=16,
                                 tickfont_size=14),
                      xaxis=dict(title='Payment Period'))
    return dcc.Graph(figure=fig)
Пример #6
0
def main():
    os.chdir('D:\Documents - HDD')
    wb = openpyxl.load_workbook('Loan_Spreadsheet.xlsx')
    type(wb)

    # changing the sheet to the "List" sheets where the loans are
    wb.active = 1
    sheet = wb.active
    loanList = []

    # creates the "Loan" object and appends to a list
    for x in range(sheet.max_row):
        name = sheet.cell(x + 1, 1)
        t = sheet.cell(x + 1, 2)
        amt = sheet.cell(x + 1, 3)
        interest = sheet.cell(x + 1, 4)
        dateBorrowed = sheet.cell(x + 1, 5)

        print(name.value, " | ", t.value, " | ", amt.value, " | ",
              interest.value, " | ", dateBorrowed.value)
        l = Loan(name, t, amt, interest, dateBorrowed)
        loanList.append(l)

    print("\n")
    loanCal(loanList)
Пример #7
0
    def book_car(self, car, name, age, licence, email, date, period, pickup, dropoff):
        customer = Customer(name, age, email, licence)
        loan = Loan(car, customer, date, period, pickup, dropoff)

        self._loans.append(loan)

        print(loan)
Пример #8
0
	def testLProgression_UT07(self):
		L = Loan('Yfirdráttur', 120000, 24, 12, False)
		self.assertEqual(L.progression(1000, 5)[1][12],0)
		self.assertEqual(L.progression(1000, 5)[1][4],76000)
		self.assertEqual(L.progression(1000, 5)[0][11],5100)
		self.assertEqual(L.progression(1000, 5)[0][3],12740)
		self.assertEqual(round(L.progression(1000, 5)[2][11]),100.0)
		self.assertEqual(round(L.progression(1000, 5)[2][3]),1740.0)
Пример #9
0
    def test_creates(self):
        LOAN1 = Loan("123-45-6789", 12345, 67890)

        self.assertTrue("123-45-6789" == LOAN1.payer_ssn, "SSN issue")
        self.assertTrue(12345 == LOAN1.prop_value, "Property value issue")
        self.assertTrue(67890 == LOAN1.loan_value, "Loan value issue")

        self.assertIsNone(LOAN1.loan_status, "Loan should not have a status")
        self.assertIsNone(LOAN1.loan_id, "Loan should not have an id")

        #

        LOAN2 = Loan("012-34-5678", 300, 400, "abc-def-ghijkl")

        self.assertTrue("012-34-5678" == LOAN2.payer_ssn, "SSN issue")
        self.assertTrue(300 == LOAN2.prop_value, "Property value issue")
        self.assertTrue(400 == LOAN2.loan_value, "Loan value issue")

        self.assertIsNone(LOAN2.loan_status, "Loan should not have a status")
        self.assertTrue("abc-def-ghijkl" == LOAN2.loan_id, "Loan should have an id")
Пример #10
0
def create_table(n_click, principal, payment, rate, ext_pay):
    loans = LoanPortfolio.LoanPortfolio()
    if ext_pay is None:
        loan = Loan.Loan(principal=principal,
                         rate=rate,
                         payment=payment,
                         extra_payment=0)
    else:
        loan = Loan.Loan(principal=principal,
                         rate=rate,
                         payment=payment,
                         extra_payment=ext_pay)
    loan.check_loan_parameters()
    loan.compute_schedule()

    loans.add_loan(loan)
    helper = Helper.Helper()
    table = helper.print_df(loan)

    if loans.get_loan_count() == 3:
        loans.aggregate()
        helper = Helper.Helper()
        table = helper.print_df(loans)

    temp = dash_table.DataTable(data=table.to_dict("records"),
                                columns=[{
                                    'id': c,
                                    'name': c
                                } for c in table.columns],
                                style_cell={'textAlign': 'center'},
                                style_as_list_view=True,
                                style_header={
                                    'backgroundColor': '#E9DADA',
                                    'fontWeight': 'bold'
                                },
                                style_table={
                                    'height': '400px',
                                    'overflowY': 'auto'
                                })

    return temp
Пример #11
0
def compute_schedule(principal, rate, payment, extra_payment):

    loan = None
    try:
        loan = Loan(principal=principal,
                    rate=rate,
                    payment=payment,
                    extra_payment=extra_payment)
        loan.check_loan_parameters()
        loan.compute_schedule()
    except ValueError as ex:
        print(ex)
    loans.add_loan(loan)
    Helper.plot(loan)
    Helper.print(loan)
    Helper.getimg(loan)

    print(round(loan.total_principal_paid, 2),
          round(loan.total_interest_paid, 2),
          round(loan.time_to_loan_termination, 0))

    if loans.get_loan_count() == 3:
        loans.aggregate()
        Helper.plot(loans)
        Helper.print(loans)
def test_loan_with_extra_payment(principal, rate, payment, extra_payment,
                                 total_principal_paid, total_interest_paid,
                                 time_to_loan_termination):
    tolerance_for_cash = 5.0
    tolerance_for_time = 1.0

    loan = None
    try:
        loan = Loan(principal=principal, rate=rate, payment=payment, extra_payment=extra_payment)
        loan.check_loan_parameters()
        loan.compute_schedule()
    except ValueError as ex:
        print(ex)
    loans.add_loan(loan)
    Helper.plot(loan)

    print(round(loan.total_principal_paid, 2), round(loan.total_interest_paid, 2),
          round(loan.time_to_loan_termination, 0))

    assert abs(loan.total_principal_paid - total_principal_paid) <= tolerance_for_cash
    assert abs(loan.total_interest_paid - total_interest_paid) <= tolerance_for_cash
    assert abs(loan.time_to_loan_termination - time_to_loan_termination) <= tolerance_for_time

    if loans.get_loan_count() == 2:
        loans.aggregate()
        Helper.plot(loans)
Пример #13
0
def end_date(principal, payment, rate, ext_pay, date_value):

    loans = LoanPortfolio.LoanPortfolio()
    if ext_pay is None:
        loan = Loan.Loan(principal=principal,
                         rate=rate,
                         payment=payment,
                         extra_payment=0)
    else:
        loan = Loan.Loan(principal=principal,
                         rate=rate,
                         payment=payment,
                         extra_payment=ext_pay)
    loan.check_loan_parameters()
    loan.compute_schedule()

    loans.add_loan(loan)
    helper = Helper.Helper()
    table = helper.print_df(loan)

    if loans.get_loan_count() == 3:
        loans.aggregate()
        helper = Helper.Helper()
        table = helper.print_df(loans)

    period = table.shape[0]
    year = int(date_value[:4])
    month = int(date_value[5:7])
    for i in range(period):
        if month == 12:
            year += 1
            month = 1
        else:
            month += 1

    month = calendar.month_name[month]
    end_date = "Your estimated loan end date is {},{}".format(month, year)

    return end_date
Пример #14
0
def table_figure2(loan_amount, interest_rate, payment, extra1, extra2, extra3,
                  start_date1):
    y = int(
        list(start_date1)[0] + list(start_date1)[1] + list(start_date1)[2] +
        list(start_date1)[3])
    m = int(list(start_date1)[5] + list(start_date1)[6])
    d = min(int(list(start_date1)[8] + list(start_date1)[9]), 28)
    start_date = date(y, m, d)
    if loan_amount != None and payment != None and interest_rate != None:
        ex1 = disting(extra1)
        ex2 = disting(extra2)
        ex3 = disting(extra3)
        loan = Loan(loan_amount, interest_rate, payment, ex1 + ex2 + ex3)
        a, b, c = compute_schedule_loan(loan_amount, interest_rate, payment,
                                        ex1 + ex2 + ex3)
        loan_noextra = Loan(loan_amount, interest_rate, payment, 0)
        df = date_trans(to_df(loan), start_date)
        df_noextra = date_trans(to_df(loan_noextra), start_date)
        new_df = pd.concat([
            df_noextra['Month'], df_noextra['End Principal'],
            df['End Principal']
        ],
                           axis=1)
        new_df.columns = ['Month', 'No extra', 'Extra all']
        new_df = new_df.append(
            {
                'Month': start_date,
                'No extra': loan_amount,
                'Extra all': loan_amount
            },
            ignore_index=True).sort_values(by='Month')
        return df.to_dict('record'), a, b, c, new_df.to_dict('record')

    else:
        df = pd.DataFrame(columns=[
            'Month', 'Begin Principal', 'Payment', 'Extra Payment',
            'Applied Principal', 'Applied Interest', 'End Principal'
        ])
        return df.to_dict('record'), 0, 0, 0, []
Пример #15
0
    def test_db_load(self):
        LOAN1 = Loan("123-45-6789", 12345, 67890)

        db = sqlite3.connect(TEST_DB)

        LOAN1.loan_status = "Awesome"
        LOAN1.save(db)

        LOAN2 = Loan(None, None, None, LOAN1.loan_id)
        self.assertTrue(LOAN2.loan_id == LOAN1.loan_id, "Loan id issue")

        LOAN2.load(db)

        self.assertTrue(LOAN2.payer_ssn == LOAN1.payer_ssn, "SSN issue")
        self.assertTrue(LOAN2.prop_value == LOAN1.prop_value, "Property value issue")
        self.assertTrue(LOAN1.loan_value == LOAN1.loan_value, "Loan value issue")
        self.assertTrue(LOAN2.loan_status == LOAN1.loan_status, "Loan status issue")

        db.close()
Пример #16
0
    def test_ssn_validation(self):
        LOAN1 = Loan(None, None, None)

        # SSN should look like AAA-GG-SSSS where A/G/S are 0-9...
        #
        for ssn in ("1234", "foo", "123456789", "329487240948372039487231", None):
            LOAN1.payer_ssn = ssn
            with self.assertRaises(FormatSSNError) as context:
                LOAN1.validate_payer_ssn()

        # ...except A cannot be 000, 666, or any 9xx
        #
        for ssn in ("000-12-3456","666-77-8888","900-12-6473","999-12-6473"):
            LOAN1.payer_ssn = ssn
            with self.assertRaises(InvalidSSNError) as context:
                LOAN1.validate_payer_ssn()
Пример #17
0
def compute_schedule(principal, rate, payment, extra_payment):

    loan = None
    try:
        loan = Loan(principal, rate, payment, extra_payment)
        loan.check_loan_parameters()
        loan.compute_schedule()
    except ValueError as ex:
        print(ex)

    return loan
Пример #18
0
def compute_schedule(principal, rate, payment, extra_payment):
    loans.schedule = {} 
    loan = None
    try:
        loan = Loan(principal=principal, rate=rate, payment=payment, extra_payment=extra_payment)
        loan.check_loan_parameters()
        loan.compute_schedule()
    except ValueError as ex:
        print(ex)
    #Add loans to portfolio and start aggregation
    loans.add_loan(loan)
    loans.aggregate()
Пример #19
0
    def test_db_save(self):
        LOAN1 = Loan("123-45-6789", 12345, 67890)

        db = sqlite3.connect(TEST_DB)

        self.assertIsNone(LOAN1.loan_id, "Loan should not have an id")
        LOAN1.save(db)
        self.assertIsNotNone(LOAN1.loan_id, "Loan should have an id after saving")

        # with the id stored, a different branch is executed
        #
        # just validating that it doesn't fail in this test, load test checks values

        LOAN1.save(db)

        db.close()
Пример #20
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-p','--principal',
                        help='Principal amount on loan',
                        required=True,
                        type=float,
                        metavar='P')
    parser.add_argument('-n','--name',
                        help='Name for specific Loan. (car, student, house)',
                        required=False,
                        type=str,
                        metavar='N',
                        default='')
    parser.add_argument('-i','--interest',
                        help=r'''Interest rate on loan in terms of decimal. 
                        If it's 5.00%% enter .05''',
                        required=True,
                        type=float,
                        metavar='I')
    parser.add_argument('-m','--monthly',
                        help='Monthly payment on loan',
                        required=True,
                        type=float,
                        metavar='M')
    
    args = parser.parse_args()

    loan1 =  Loan.Loan(args.principal, args.interest)
    months = 0
    monthly_pay = args.monthly
    while(not loan1.is_zero()):
        months += 1
        loan1.pay(monthly_pay)
    message = 'Time to pay off {}loan: {} years and {} months'.format(args.name+' ', months//12, months % 12)
    print(message)
    message = 'Total interest paid over time: ${:,.2f}'.format(loan1.interest_paid)
    print(message)
Пример #21
0
def Main(area, cp, months, tof):

    # Inputs

    # Ratio of KWp by area [KWP/m2], value obtained from the manufacturer technical sheet
    wp = 0.145  # ratio in [kwp/m2]

    #Area of the solar panels in [m2]

    print('area es == ' + str(area))
    print(' postal code is== ' + str(cp))
    #area=100 #m2
    #postal code
    #cp=int(raw_input("What is your postal code??"))
    #cp=44670
    #Exchange rate

    exchangeRate = ExchangeRate.exchange()  #[mxn/usd]
    now = datetime.datetime.now()
    day = now.strftime
    #print (now.strftime("%Y-%m-%d %H:%M"))
    print(' Exhange rate: ', str(exchangeRate) + ' mxn/usd')
    #solar production year estimate_bandwidth    kw*h/yr
    irradiationMean = SolarProductionN.myfunc(wp, cp)
    #solarP=SolarProductionN.myfunc(wp,cp)*area*wp
    solarP = irradiationMean * area * wp
    irradiationDistribution = Distribution.distribution(
        irradiationMean)  #irradiation distribution by month [kwh/hwp/year]
    print('irradiation distribution: ' + str(irradiationDistribution) +
          'kwh/kwp/yr.')
    print('Anual solar output:  ' + str(solarP) + ' kw*h/yr')

    #Total cost of install  $
    #iInv=15265
    #print(area*wp)
    if (area * wp) < 4:
        iInv = area * wp * 1840 * 1.4
        print('menor a 4')
    elif (area * wp) > 4 and (area * wp) < 10:
        iInv = area * wp * 1509 * 1.4
        print('entre 4 y 10')
    else:
        iInv = area * wp * 1153 * 1.4
        print('mayor a 10')
    print('inivital investment:  ' + str(iInv) + ' $ USD')

    #Discount rate
    dRate = 0.0772
    dRateM = (1 + dRate)**(1 / 12) - 1
    print(dRateM)
    #number of months
    #months=12*25
    '''
    #Tax benefits
    taxBenefit=int(raw_input('Type the percentage of tax benefit'))/100
    iInv=(1-taxBenefit)*iInv
    '''
    #Loan
    #percentageLoan= int(raw_input('Percentage of borrowed from the initial investment'))/100
    percentageLoan = 0.44
    installment = Loan.loan(dRateM, months, percentageLoan * iInv)

    #Energy price per [$/KW*h]  Type of user
    #type=raw_input('Enter type of user:residential,industrial or business')

    energyP = EnergyPriceN.allocation(tof, solarP, cp) * float(exchangeRate)
    print('Unit price:' + str(energyP) + ' $/kwh')
    #energyP=0.147
    #energyP=2.6811

    #electricity price increase per year    1/yr
    electricityI = 0.02

    #solar panel yearly degradation 1/yr
    panelD = 0.005

    #Minimum fees $/month
    minimumFee = 0

    #Cash flow model
    vTime = []
    vTimeY = []
    mEProduction = []
    mEProduction.append(0)
    mdistribution = []
    mdistribution.append(0)
    vDegradation = []
    vDegradation.append(0)
    eGeneration = []
    eGeneration.append(0)
    MinFees = []
    MinFees.append(0)
    cashFlow = []
    cashFlowY = []
    netCashFlow = []
    netCashFlowY = []
    cashFlow.append(-iInv)
    netCashFlow.append(-iInv)

    #Columns:Time interval[month]
    for i in range(months + 1):
        vTime.append(i)

    #Columns: Monthly energy production[kw*h],Degradation[%],Energy generation by month[kw*h], minimum fee [usd/month], Cash flow [usd/month], netcashflow [usd/month]
    for i in range(1, months + 1):
        j = i % 12
        if j == 0:
            j = 12
        #print ('j es igual    '+str(j))
        mProduction = round(solarP / 12, 7)  # delete round
        mEProduction.append(mProduction)
        mProductionD = float(irradiationDistribution[j - 1]) * area * wp
        mdistribution.append(mProductionD)

        degradation = round(i * panelD / 12, 7)
        vDegradation.append(degradation)

        generation = round(mProductionD * (1 - degradation),
                           7)  # takes into account the distributed energy
        eGeneration.append(generation)

        MinFees.append(minimumFee)

        cash = round(
            generation * energyP * (1 + i * electricityI / (12)),
            7) - minimumFee - Loan.monthlyInstallmentM[i]  # aqui esta el peine
        cashFlow.append(cash)

        net = math.fsum(cashFlow)
        netCashFlow.append(net)

    # Output Parameters

    #print(cashFlow)

    # from months to years #optimize algorithm

    years = int(months / 12)
    for i in range(years):
        vTimeY.append(i + 1)
        sum = 0
        add = 0
        #k=i+1
        for j in range(12):
            #print (j)
            position = j + i * 12 + 1
            #print(position)
            sum = sum + netCashFlow[position]
            add = add + cashFlow[position]

        if i == 0:
            sum2 = sum - iInv
            netCashFlowY.append(sum2)
            add2 = add - iInv
            cashFlowY.append(add2)
        else:
            netCashFlowY.append(sum)
            cashFlowY.append(add)

    irr = np.irr(cashFlow)
    print('IRR: %s ' % irr)
    irrY = np.irr(cashFlowY)
    print('IRR Year: %s ' % irrY)

    presentValue = np.npv(dRateM, netCashFlow)
    print('Net Present value: ' + str(presentValue))

    #print(netCashFlow)
    #print(netCashFlowY)

    print('otro mas')

    presentM = []
    timeP = []
    for i in range(0, 30):
        x = (i + 1) / 100
        timeP.append(x)
        #present=np.npv(x,netCashFlowY)
        present = np.npv(x, cashFlowY)
        presentM.append(present)
    #print(presentM)

    #----CSV----CSV----CSV----CSV----CSV----CSV----CSV----CSV----CSV----CSV----CSV----CSV----CSV----CSV----CSV----CSV
    with open('mycsv.csv', 'w', newline='') as f:
        #fieldnames=['Period','Monthly energy production','Panel degradation','Energy generation','Minimum Fees','Cashflow','Net cashflow']
        fieldnames = [
            'Period', 'Monthly energy production',
            'Distributed Monthly energy production', 'Panel degradation',
            'Energy generation', 'Minimum Fees', 'Monthly installment',
            'Cashflow', 'Net cashflow'
        ]
        thewriter = csv.DictWriter(f, fieldnames=fieldnames)

        thewriter.writeheader()
        #thewriter.writerow({'column 1':'juan','column2':'ale','column 3':'raquel'})
        for i in range(len(vTime)):
            period = vTime[i]
            pro = mEProduction[i]
            dis = mdistribution[i]
            deg = vDegradation[i]
            gen = eGeneration[i]
            #fee=MinFees[i]
            mon = monthlyInstallmentM[i]
            cas = cashFlow[i]
            net = netCashFlow[i]

            thewriter.writerow({
                'Period': period,
                'Monthly energy production': pro,
                'Distributed Monthly energy production': dis,
                'Panel degradation': deg,
                'Energy generation': gen,
                'Monthly installment': mon,
                'Cashflow': cas,
                'Net cashflow': net
            })

    #----Plots----Plots----Plots----Plots----Plots----Plots----Plots----Plots----Plots----Plots----Plots----Plots

    area2 = 200
    k = area / area2
    case2 = [i * k for i in netCashFlowY]

    grafica = plt.figure(2)
    ax = grafica.add_subplot(421)
    ax.bar(vTimeY, netCashFlowY, color=(1.0, 0.5, 0.62))
    ax.set_ylabel('Cash flow')
    ax.set_xlabel('Years')
    ax.set_title('Cash flow solar panels 25 years')
    ax.grid(color='b', linestyle='-', linewidth=0.1)

    ax = grafica.add_subplot(422)
    ax.plot(vTime, netCashFlow)
    ax.get_yaxis().set_major_formatter(
        plt.FuncFormatter(lambda x, loc: "{:,}".format(int(x))))
    ax.set_ylabel('Cash flow')
    ax.set_xlabel('Months')
    ax.set_title('Break even point project 1')
    ax.grid(color='b', linestyle='-', linewidth=0.1)

    plt.axhline(linewidth=1, color='r')

    ax = grafica.add_subplot(425)
    ax.plot(vTimeY, netCashFlowY, 'g', vTimeY, case2, 'r')
    ax.get_yaxis().set_major_formatter(
        plt.FuncFormatter(lambda x, loc: "{:,}".format(int(x))))
    #ax.set_xticks(ax.get_xticks()[::1])# number of times the x axis is divided
    ax.set_ylabel('Cash flow')
    ax.set_xlabel('Years')
    ax.set_title('Revenue of two projects')
    ax.grid(color='b', linestyle='-', linewidth=0.1)
    p1 = str(area) + ' m2 project '
    p2 = str(area2) + ' m2 project'
    ax.legend([p1, p2])

    ax = grafica.add_subplot(426)
    ax.plot(timeP, presentM)
    ax.get_yaxis().set_major_formatter(
        plt.FuncFormatter(lambda x, loc: "{:,}".format(int(x))))
    #ax.set_xticks(ax.get_xticks()[::1])# number of times the x axis is divided
    ax.set_ylabel('Cash flow')
    ax.set_xlabel('Discount rate')
    ax.set_title('IRR project ' + p1)
    ax.grid(color='b', linestyle='-', linewidth=0.1)
    plt.axhline(linewidth=1, color='r')
    plt.show()
Пример #22
0
	def testLpayProgression_UT08(self):
		L = Loan('Yfirdráttur', 120000, 24, 12, False)
		self.assertEqual(L.payProgression(1000, 5)[11],5100)
		self.assertEqual(L.payProgression(1000, 5)[3],12740)
Пример #23
0
	def testLdebtProgression_UT09(self):
		L = Loan('Yfirdráttur', 120000, 24, 12, False)
		self.assertEqual(L.debtProgression(1000, 5)[12],0)
		self.assertEqual(L.debtProgression(1000, 5)[4],76000)
Пример #24
0
	def testLtotInterest_UT10(self):
		L = Loan('Yfirdráttur', 120000, 24, 12, False)
		self.assertEqual(L.totInterest(1000, 5),14700)
Пример #25
0
	def testLinterestM_UT11(self):
		L = Loan('Yfirdráttur', 120000, 24, 12, False)
		self.assertEqual(L.interestM(1000, 5, 9),13800)
Пример #26
0
	def testLdatLoanDebt_UT12(self):
		L = Loan('Yfirdráttur', 120000, 24, 12, False)
		self.assertEqual(round(L.datLoanDebt(1000, 5)[1][11]),100)
		self.assertEqual(round(L.datLoanDebt(1000, 5)[1][3]),77740)
Пример #27
0
# -*- coding: utf-8 -*-
from Savings import *
from Loan import *
from Calculator import *
#from storage import *
from Plot import *

#Profar Loan og Savings:
S1 = Savings('Ubersparnadur', 100000, 1.7, True, 12)
S2 = Savings('Sparigris', 100000, 3.5, False, 3)

L1 = Loan('Husnaedislan', 30000000, 1.3, 240, True)
L2 = Loan('Yfirdrattur', 450000, 20, 6, False)
print L1
print
print L2

print S1
print '\nEf madur borgar 1000 kr inn a sparnadinn naestu 6 manudi ta verdur troun reikningsins naestu 12 manudi:'
print S1.printProgression(1000, 6, 12)
print '\nEf madur borgar 0 kr inn a sparnadinn naestu 6 manudi ta verdur troun reikningsins naestu 12 manudi:'
print S1.printProgression(1000, 0, 12)
print '\nMed tvi ad leggja 1000 kr inn a manudi inn ta geturdu tekid ut eftirfarandi upphaed eftir 12 manudi:' #Ath verdur ad haetta ad leggja inn svo binditimi klarist adur en tekid er ut
print S1.saveforM(1000, 12)
print '\nMed tvi ad leggja 1000 kr inn a manudi inn ta verdur stadan a reikningunum ordin haerri en 250.000 eftir:'
print S1.saveuptoX(1000, 250000)
print
print S2
print '\nEf madur borgar 1000 kr inn a sparnadinn naestu 6 manudi ta verdur troun reikningsins naestu 12 manudi:'
print S2.printProgression(1000, 6, 12)
print '\nEf madur borgar 0 kr inn a sparnadinn naestu 6 manudi ta verdur troun reikningsins naestu 12 manudi:'
Пример #28
0
	def testLdatLoanPay_UT13(self):
		L = Loan('Yfirdráttur', 120000, 24, 12, False)
		self.assertEqual(round(L.datLoanPay(1000, 5)[1][11]),5100)
		self.assertEqual(round(L.datLoanPay(1000, 5)[1][3]),12740)
Пример #29
0
def compute_schedule_loan(principal, rate, payment, extra_payment):
    loan = Loan(principal=principal, rate=rate, payment=payment, extra_payment=extra_payment)
    loan.check_loan_parameters()
    loan.compute_schedule()
    return round(loan.total_principal_paid, 2) + round(loan.total_interest_paid, 2), round(loan.total_interest_paid, 2), round(loan.time_to_loan_termination, 0)
Пример #30
0
def update_output_div(principal, payment, rate, extra_payment, c1, c2, c3,
                      btn1, btn2, bt3):
    global loans
    changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]
    if 'btn-nclicks-1' in changed_id:
        loan = None
        try:
            loan = Loan(principal=float(principal),
                        rate=float(rate),
                        payment=float(payment),
                        extra_payment=float(extra_payment))
            loan.check_loan_parameters()
            loan.compute_schedule()
        except ValueError as ex:
            print(ex)

        loans.add_loan(loan)
        msg = 'add loan success'
        loans.aggregate()
        #        msg = re.sub('\r\n', '<br>', str(Helper.print(loans)))
        return html.Div([
            html.H5('Current loan: '),
            html.Table([
                html.Thead(
                    html.Tr([
                        html.Th(col) for col in [
                            'Payment Number', 'Begin Principal', 'Payment',
                            'Extra Payment', 'Applied Principal',
                            'Applied Interest', 'End Principal'
                        ]
                    ])),
                html.Tbody([
                    html.Tr([
                        html.Td(Helper.display(float(pay[i])))
                        for i in range(7)
                    ]) for pay in loan.schedule.values()
                ])
            ]),
            dcc.Graph(figure=Helper.getimg(loan)),
            html.H5('ALL loans: '),
            html.Table([
                html.Thead(
                    html.Tr([
                        html.Th(col) for col in [
                            'Payment Number', 'Begin Principal', 'Payment',
                            'Extra Payment', 'Applied Principal',
                            'Applied Interest', 'End Principal'
                        ]
                    ])),
                html.Tbody([
                    html.Tr([
                        html.Td(Helper.display(float(pay[i])))
                        for i in range(7)
                    ]) for pay in loans.schedule.values()
                ])
            ]),
            dcc.Graph(figure=Helper.getimg(loans))
        ])
    elif 'btn-nclicks-2' in changed_id:
        loans = LoanPortfolio()
        msg = 'clear success'
    elif 'btn-nclicks-3' in changed_id:
        loan_impacts = LoanImpacts(
            principal=float(principal),
            rate=float(rate),
            payment=float(payment),
            extra_payment=float(extra_payment),
            contributions=[float(c1), float(c2),
                           float(c3)])
        impdata = loan_impacts.compute_impacts()
        return html.Div([
            html.H5('Loan impact: '),
            html.Table([
                html.Thead(
                    html.Tr([
                        html.Th(col) for col in [
                            'Index', 'InterestPaid', 'Duration', 'MIInterest',
                            'MIDuration'
                        ]
                    ])),
                html.Tbody([
                    html.Tr([html.Td(pay[i]) for i in range(5)])
                    for pay in impdata
                ])
            ])
        ])
    else:
        msg = 'None of the buttons have been clicked yet'

    return 'Output: {}'.format(msg)
Пример #31
0
def displayMenu():
    print("Menu:\n"
          "1. Balance Display\n"
          "2. Deposit Money\n"
          "3. Withdraw Money\n"
          "4. Interest\n"
          "5. Loans\n"
          "6. Donate Money\n"
          "7. Stocks\n"
          "8. ATM\n"
          "9. Insurance\n"
          "10. Recent Transactions\n"
          "11. Shop\n"
          "0. Exit")
    choice = str(input("Type your choice number. \n"))

    if choice == "1":
        print("Your balance is: ", Balance.balance)
        pressAnyKey()
        displayMenu()

    elif choice == "2":
        Transactions.depositMoney()
        pressAnyKey()
        displayMenu()

    elif choice == "3":
        Transactions.withdrawMoney()
        pressAnyKey()
        displayMenu()

    elif choice == "4":
        Interest.interestCalculation()
        Interest.interestMoney()
        pressAnyKey()
        displayMenu()

    elif choice == "5":
        Loan.performLoan()
        pressAnyKey()
        displayMenu()

    elif choice == "6":
        Transactions.donateMoney()
        pressAnyKey()
        displayMenu()

    elif choice == "7":
        StockMarket.options()
        pressAnyKey()
        displayMenu()

    elif choice == "8":
        ATM.atmSecurity()
        pressAnyKey()
        displayMenu()

    elif choice == "9":
        Insurance.insuranceType()
        pressAnyKey()
        displayMenu()

    elif choice == "10":
        RecentTransactions.display()
        pressAnyKey()
        displayMenu()

    elif choice == "11":
        Shop.startShop()
        pressAnyKey()
        displayMenu()

    elif choice == "0":
        print("Goodbye...")
        exit()

    else:
        print("Please enter a valid thing to do.")
        displayMenu()
Пример #32
0
dRateM=(1+dRate)**(1/12)-1
dRate2=0.115
dRateM2=(1+dRate2)**(1/12)-1
print (dRateM)
#number of months
months=12*25

'''
#Tax benefits
taxBenefit=int(raw_input('Type the percentage of tax benefit'))/100
iInv=(1-taxBenefit)*iInv
'''
#Loan
#percentageLoan= int(raw_input('Percentage of borrowed from the initial investment'))/100
percentageLoan=0.5
installment= Loan.loan(dRateM2,months,percentageLoan*iInv)   


#Energy price per [$/KW*h]  Type of user
#type=raw_input('Enter type of user:residential,industrial or business')

energyP=EnergyPriceN.allocation('residential', solarP, cp)*float(exchangeRate)
print ('Unit price:'+str(energyP)+' $/kwh')
#energyP=0.147
#energyP=2.6811

#electricity price increase per year    1/yr
electricityI=0.02

#solar panel yearly degradation 1/yr
panelD=0.005
Пример #33
0
 def intoloan(self, account):
     LoginSupport.destroy_window()
     Loan.vp_start_gui(account, accountid)
Пример #34
0
    def test_ltv_validation(self):
        LOAN1 = Loan(None, None, None)

        LOAN1.prop_value = 5000

        # 100% loan amount, too high!
        #
        LOAN1.loan_value = LOAN1.prop_value

        with self.assertRaises(ExcessLoanToValueError) as context:
            LOAN1.validate_ltv()

        # 50% loan amount, still too much
        #
        LOAN1.loan_value = LOAN1.prop_value * 0.5

        with self.assertRaises(ExcessLoanToValueError) as context:
            LOAN1.validate_ltv()

        # 40% loan amount is the cap
        #
        LOAN1.loan_value = LOAN1.prop_value * 0.4
        LOAN1.validate_ltv()

        # And lower is OK, too
        #
        LOAN1.loan_value = LOAN1.prop_value * 0.1
        LOAN1.validate_ltv()
Пример #35
0
        "Num of Lenders"))
    for i in range(0, len(data)):
        print("{:<10} {:<15} {:<15} {:<10} {:<15} {:<5}".format(
            data[i].id, data[i].loan_amount, data[i].country_name,
            data[i].status, data[i].time_to_raise, data[i].num_lenders_total))


with open('data.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            line_count += 1
            continue
        # print(row[1])
        data.append(Loan(row[0], row[1], row[2], row[3], row[4], row[5]))
        line_count += 1


def find_total_amount(data):
    sum = 0
    for i in range(0, 25):  # data samples = 25
        sum += int(data[i].loan_amount)
    return sum


def find_average_amount(data):
    sum = 0
    for i in range(0, 25):  # data samples = 25
        sum += int(data[i].loan_amount)
    return sum / 25