Please see a tutorial. Also join https://web.libera.chat/
-- On Thu, Feb 17, 2022 at 9:48 PM Dushime Mudahera Richard <mudaherarich@gmail.com> wrote:
--Questioni want to capture the enteredLoanAmountage enteredAge enteredTerm, and gender alsofrom the form that i have in signup page then calculations will follow and print out the results in a tableAs per now when i run in the terminal i can enter all the values and get the results in the terminalor i want to get the inputs from the user form that i created and display it in a tablehis is my form.pyfrom django import formsfrom crispy_forms.helper import FormHelperfrom crispy_forms.layout import Submitclass BasicForm(forms.Form):GENDERS = (('M', 'Male'),('F', 'Female'))enteredLoanAmount = forms.CharField()Enter_age = forms.CharField()Enter_loan_term = forms.CharField()gender = forms.ChoiceField(widget=forms.RadioSelect, choices=GENDERS)# We should use a validator to make sure# the user enters a valid number formatdef __init__(self,*args, **kwargs):super().__init__(*args,*kwargs)self.helper = FormHelper(self)self.helper.form.method='post'self.helper.add_input(Submit('Save','Submit'))my templates{% extends 'base.html' %}{% load crispy_forms_tags %}{% block content %}<div class="card" style = "width:25rem; margin:auto;"><div class="card-header" style="background-color:#248cd1; color:white;">Create your Order</div><div class="card-body"><form method="POST" action="">{% csrf_token %}{% crispy form %}</form></div></div>{% endblock %}my viewsfrom django.shortcuts import renderimport mathimport pandas as pdimport numpy as npimport numpy_financial as npffrom .forms import BasicFormdef signup(request):if request.method == 'POST':form = BasicForm(request.POST)if form.is_valid():# Entering the loan amountisCorrectAmount = Truewhile isCorrectAmount:enteredLoanAmount = request.POST.get(float(input("Enter Loan amount (Min - 1,000,000): ")))if enteredLoanAmount < 1_000_000:print("Minimum Loan amount is 1,000,000")enteredLoanAmount = float(input("Enter Loan amount (Min - 1,000,000): "))else:isCorrectAmount = False# Entering the ageisCorrectAge = Truewhile isCorrectAge:enteredAge = int(input("Enter Age (18 - 50 years): "))if enteredAge < 18 or enteredAge > 50:print("Sorry, age does not meet criteria!")enteredAge = int(input("Enter Age (18 - 50 years):"))else:isCorrectAge = False# Entering the loan termisCorrectTerm = Truewhile isCorrectTerm:enteredTerm = int(input("Enter Loan term (3 - 35 years): "))if enteredTerm < 3 or enteredTerm > 35:print("Sorry, loan term does not meet criteria!")enteredTerm = int(input("Enter Loan term (3 - 35 years):"))else:isCorrectTerm = False# Entering the genderenteredGender = input("Enter Gender (MALE or FEMALE): ")# Assumptionsgeneral_assumptions = pd.read_csv('data/general_assumptions.csv')surrender_rates = pd.read_csv('data/surrender_rates.csv')mortality_rates = pd.read_csv('data/mortality_rates.csv')disability_rates = pd.read_csv('data/disability_rates.csv')critical_illness = pd.read_csv('data/critical_illness_rates.csv')amortization_assumptions = pd.read_csv('data/amortization_assumptions.csv')sumAssured = enteredLoanAmountcoverExpiry = enteredAge + enteredTermif coverExpiry > 55:print("Cover exceeds 55 years !")def vlookup(value,df,coli,colo):"""vlookup function to reference other tables"""return next(iter(df.loc[df[coli]==value][colo]), None)# Mortality Calculationsradix = float((general_assumptions[(general_assumptions['assumption'] == 'radix')]).amount)def mortality_calc():""" Function to do calculations based on mortality rates """mortality = []lx = []dx = []Dx = []Nx = []Cx = []Mx = []Rx = []Sx = []if enteredGender == 'male' or enteredGender == 'MALE':qx = 'Graduated Rates(qx) Males'else:qx = 'Graduated Rates(qx) Females'for i in range(len(mortality_rates)):agex = 18 + iif i == 0:lx_value = radixlx.append(lx_value)else:lx_value = (lx[-1]) - (vlookup(agex,mortality_rates,'age x',qx)*lx[-1])lx.append(lx_value)Dx_value = (lx_value * ((1+0.04)**(-agex)))Dx.append(Dx_value)for i in range(len(mortality_rates)):agex = 18 + itry:dx_value = lx[i] - lx[i+1]except IndexError:dx_value = lx[-1]dx.append(dx_value)Nx_value = sum(Dx[i:])Nx.append(Nx_value)Cx_value = ((1/((1+0.04)**(agex+1))) * dx_value)Cx.append(Cx_value)for i in range(len(mortality_rates)):Mx_value = sum(Cx[i:])Mx.append(Mx_value)for i in range(len(mortality_rates)):Rx_value = sum(Mx[i:])Rx.append(Rx_value)for i in range(len(mortality_rates)):Sx_value = sum(Nx[i:])Sx.append(Sx_value)for i in range(len(mortality_rates)):agex = 18 + iqx_val = (vlookup(agex,mortality_rates,'age x',qx))mortality.append({'age x': agex, qx : qx_val, 'lx': lx[i], 'dx': dx[i], 'Dx': Dx[i],'Nx': Nx[i], 'Cx': Cx[i], 'Mx': Mx[i], 'Rx': Rx[i], 'Sx': Sx[i]})return pd.DataFrame(mortality)mortality_calculations = mortality_calc()numpy_mortality = np.array(mortality_calculations)# Assurances and Annuitiesdef assurances_calc():""" Function to calculate assurances and annuities """aNa = []ax_val_list = []qx_list = []lx_list = []Mx_list = []Dx = []axn_list = []ax_n_list = []dxn_list = []Ax_list = []Axn_list = []Ax1n_list = []t1v_list = []if enteredGender == 'male' or enteredGender == 'MALE':qx = 'Graduated Rates(qx) Males'else:qx = 'Graduated Rates(qx) Females'for i in range(46):X = enteredAge + iqx_val = vlookup(X, mortality_calculations, 'age x', qx)qx_list.append(qx_val)lx = vlookup(X, mortality_calculations, 'age x', 'lx')lx_list.append(lx)Dx_val = vlookup(X, mortality_calculations, 'age x', 'Dx')Dx.append(Dx_val)Mx = vlookup(X, mortality_calculations, 'age x', 'Mx')Mx_list.append(Mx)for i in range(46):t = i + 1X = enteredAge + iax_val = (sum(Dx[i:]))/Dx[i]ax_val_list.append(ax_val)if i == 0:n = enteredTermif n < 1:n = 0aNa.append({'t': t, 'X': X, 'qx': qx_list[i], 'lx': lx_list[i], 'Dx': Dx[i],'Mx': Mx_list[i], 'ax': ax_val_list[i], 'n': n})n = n-1ana_dataframe = pd.DataFrame(aNa)for i in range(46):X = enteredAge + iif i == 0:n = enteredTermif n < 1:n = 0axn = vlookup((X+n), ana_dataframe, 'X', 'ax')axn_list.append(axn)dxn = vlookup((X+n), ana_dataframe, 'X', 'Dx')dxn_list.append(dxn)n = n - 1ax_n = ax_val_list[i] - ((dxn/Dx[i])*axn)ax_n_list.append(ax_n)Ax = Mx_list[i]/Dx[i]Ax_list.append(Ax)ana_dataframe['ax+n'] = axn_listana_dataframe['Dx+n'] = dxn_listana_dataframe['ax:n'] = ax_n_listana_dataframe['Ax'] = Ax_listfor i in range(46):X = enteredAge + iif i == 0:n = enteredTermif n < 1:n = 0Axn = vlookup((X+n), ana_dataframe, 'X', 'Ax')Axn_list.append(Axn)n = n - 1ana_dataframe['Ax+n'] = Axn_listfor i in range(46):Ax1n = Ax_list[i] - ((dxn_list[i]/Dx[i])*Axn_list[i])Ax1n_list.append(Ax1n)ana_dataframe['Ax1:n'] = Ax1n_list#Net Premiumnet_premium = (enteredLoanAmount*Ax1n_list[0])/ax_n_list[0]for i in range(46):t = i+1if i == 0:t1v = 0elif t < enteredTerm:t1v = (enteredLoanAmount*Ax1n_list[i]) - (net_premium*ax_n_list[i])else:t1v = 0t1v_list.append(t1v)ana_dataframe['t-1 v reserve'] = t1v_listreturn ana_dataframeassurances = assurances_calc()numpy_assurances = np.array(assurances)def create_decrements_table():""" function to create the decrements table """decrements_table = []years = 36if enteredGender == 'male' or enteredGender == 'MALE':dx = 'Graduated Rates(qx) Males'bx = 'males'else:dx = 'Graduated Rates(qx) Females'bx = 'females'for year in range(years):if year == 0:agex = enteredAget_1apx = 1else:agex = enteredAge + yeart_1apx = decrements_table[year-1]['t-1apx'] * decrements_table[year-1]['apx']if (year+1) <= enteredTerm:qdx = vlookup(agex,mortality_calculations,'age x',dx)qbx = vlookup(agex,disability_rates,'age x',bx)qcx = vlookup(agex,critical_illness,'age x',bx)aqdx = qdx*(1-(0.5*(qbx+qcx))+((1/3)*qbx*qcx))aqbx = qbx*(1-(0.5*(qdx+qcx))+((1/3)*qdx*qcx))aqcx = qcx*(1-(0.5*(qbx+qdx))+((1/3)*qbx*qdx))apx = 1-aqdx-aqbxelse:qdx = 0qbx = qdxqcx = qdxaqdx = qdxaqbx = qdxaqcx = qdxapx = qdxagex = qdxdecrements_table.append({'year t':year+1, 'age':agex, 'qdx':qdx, 'qbx':qbx, 'qcx':qcx, 'aqdx':aqdx, 'aqbx':aqbx,'aqcx':aqcx, 'apx':apx, 't-1apx':t_1apx})return pd.DataFrame(decrements_table)# Create the decrements tabledecrements_table = create_decrements_table()numpy_decrements = np.array(decrements_table)def create_amortization_table():""" Function to create the armotization table """amortization_table = []period = enteredTerm + 1principal = enteredLoanAmountinstallment = npf.pmt(0.042/1,enteredTerm,-principal)for i in range(period):if i == 0:payment = 0interest = 0new_principal = 0new_balance = principalelse:payment = installmentinterest = npf.ipmt(0.042/1,i,enteredTerm,-principal)new_principal = npf.ppmt(0.042/1,i,enteredTerm,-principal)new_balance = amortization_table[i-1]['Balance'] - new_principalamortization_table.append({'Period':i, 'Payment':payment, 'Interest':interest, 'Principal':new_principal,'Balance':new_balance})return pd.DataFrame(amortization_table)# Create the amortization tableamortization_table = create_amortization_table()numpy_amortization = np.array(amortization_table)# Determining Premiums and Profitinitial_expenses = 0.35second_year_expenses = 0.15subsequent_years_expenses = 0.10initial_commission = 0.20second_year_commission = 0.07subsequent_year_commission = 0.05critical_illness_rate = 0.5risk_discount_rate = 0.1annual_premium = (enteredLoanAmount*numpy_assurances[0][13])/(-0.55+0.37+numpy_assurances[0][10]-0.37*numpy_assurances[0][10])def calculate_premiums_and_profit():"""Function to calculate premiums and profit """premiums = []period = enteredTerm + 1interest_rate = 0.1for i in range(period):t = i + 1if i == 0:expenses = initial_expenses * annual_premiumcommission = initial_commission * annual_premiumelif i == 1:expenses = second_year_expenses * annual_premiumcommission = second_year_commission * annual_premiumelse:expenses = subsequent_years_expenses * annual_premiumcommission = subsequent_year_commission * annual_premiumnet_cashflow = annual_premium - expenses - commissioninterest = net_cashflow * interest_ratetry:loan_death_cost = numpy_decrements[i][5] * numpy_amortization[i+1][-1]remaining_balance = (enteredLoanAmount-numpy_amortization[i+1][-1])*numpy_decrements[i][5]disability_cost = numpy_decrements[i][6]*numpy_amortization[i+1][-1]critical_illness_cost = critical_illness_rate*numpy_amortization[i+1][-1]*numpy_decrements[i][7]cost_increase_provisions = (numpy_decrements[i][8]*numpy_assurances[i+1][-1]) - numpy_assurances[i][-1]except IndexError:passprofit = net_cashflow+interest-loan_death_cost-remaining_balance-disability_cost-cost_increase_provisionsprofit_signature = profit*numpy_decrements[i][-1]discount_vt = (1/(1+risk_discount_rate))**tdiscounted_profit = profit_signature*discount_vtdiscount_vt1 = (1/(1+risk_discount_rate))**(t-1)discounted_premium = discount_vt1*annual_premium*numpy_decrements[i][-1]premiums.append({'time t': t, 'Premium': annual_premium, 'Expenses': expenses, 'Commission': commission,'Net cashflow': net_cashflow, 'Interest': interest,'Outstanding loan death cost': loan_death_cost,'Remaining balance to beneficiaries': remaining_balance, 'Disability cost': disability_cost,'Critical illness cost': critical_illness_cost, 'Cost of increase in provisions': cost_increase_provisions,'Profit':profit, 'Profit Signature': profit_signature, 'Discount vt': discount_vt,'Discounted profit': discounted_profit, 'Discount vt-1': discount_vt1, 'Discounted Premium': discounted_premium})return pd.DataFrame(premiums)premiums_and_profit = calculate_premiums_and_profit()# NPV of profitsNPV_profits = sum(premiums_and_profit['Profit'])# NPV of premiumsNPV_premiums = sum(premiums_and_profit['Discounted Premium'])# Profit Marginprofit_margin = round((NPV_profits/NPV_premiums)*100,2)# Round off annual premium to 0 decimal placesannual_premium = round(annual_premium,0)print("\n\n############## PROGRAM OUTPUT ##############")print(f"\nAnnual Premium to pay: UGX {annual_premium}")print(f"\nCover up to: {coverExpiry} years of age")print(f"\nProfit Margin: {profit_margin}%")else:form = BasicForm()return render(request, 'signup.html', {'form': form})def home(request):form = BasicForm(request.POST)return render(request, 'base.html')
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAJCm56K1ivyj%3DCpgaCgqWDhzn8E5WteK%3D37w_LmUmWHxDtXj6Q%40mail.gmail.com.
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACaE8x5hvWoaTnfnsScvsh0_6qOxH8zgOuEpkP_YWkqwR1jzsQ%40mail.gmail.com.
No comments:
Post a Comment