def test_broken_by_loan(self): loan = Loan() loan.cms = 100 loan.borrower_income_1 = 0 loan.borrower_income_2 = 0 self.assertTrue(self.loan_exception.broken_by_loan(loan))
def test_broken_by_loan(self): loan = Loan() loan.current_index = 'FIX' loan.current_margin = 5 loan.current_interest_rate = 3 self.assertTrue(self.loan_exception.broken_by_loan(loan))
def test_broken_by_loan_margin_match(self): loan = Loan() loan.current_index = 'NOT-FIX' loan.current_margin = 5 loan.current_interest_rate = 3 self.assertFalse(self.loan_exception.broken_by_loan(loan))
def test_broken_by_loan_income_sufficient(self): loan = Loan() loan.cms = 100 loan.borrower_income_1 = 1200 loan.borrower_income_2 = 1200 self.assertFalse(self.loan_exception.broken_by_loan(loan))
def add(self, new_item: Dict) -> List[Dict]: for book_to_loan in new_item['books']: book = Book.query.get(book_to_loan['id']) # book_type: BookType = BookType.query.get(book.book_type_id) if book.book_type_id else None if book.book_type: duration = { book.book_type.loan_duration_unit.lower(): +book.book_type.loan_duration } delta = relativedelta(**duration) else: delta = relativedelta(months=1) due_date = self._now + delta loan = Loan(book_id=book.id, sub_id=new_item['sub_id'], loan_date=int(self._now.timestamp()), due_date=int(due_date.timestamp())) db.session.add(loan) db.session.flush() book.loan_id = loan.id db.session.add(book) try: db.session.commit() except Exception as exc: print(f'Something went wrong: {exc}') db.session.rollback() finally: loans = Loan.query.filter_by(sub_id=new_item['sub_id']).all() loans = [loan.to_dict() for loan in loans] return loans
def test_get_loan_penalty(self): testcases = [ ('U', 0), ('P', 2), ('N', 4), ('L', 6), ('M', 8), ('B', 10), ] for category, penalty in testcases: with self.subTest(category=category): loan = Loan() loan.fitch_product_category = category self.assertEqual(penalty, self.loan_exception.get_loan_penalty(loan))
def newloan(): now = datetime.datetime.now() form = Newloan() msgs = "" if request.method == 'POST' and form.validate_on_submit(): check = Loan.query.filter_by(loanerid=form.memberid.data).first() query = MemberJoin.query.filter_by(memberid=form.memberid.data).first() if query is None: msgs = 'Student does not exist!' return render_template('loan_add.html', form=form, msgs=msgs) if check is None: if form.attendtype.data == 'Unpaid': db.session.add( Loan(loanerid=form.memberid.data, amount=form.amount.data, loan_colyear=now.year, date=now, status=form.attendtype.data, loan_orgcode=current_user.orgCode)) db.session.commit() flash(' Student recorded successfully!') return redirect(url_for('newloan')) if form.attendtype.data == 'Paid': db.session.add( Loan(loanerid=form.memberid.data, amount=form.amount.data, loan_colyear=now.year, date=now, status=form.attendtype.data, loan_orgcode=current_user.orgCode)) db.session.commit() flash(' Student recorded successfully!') return render_template('loan_add.html', form=form, msgs=msgs) elif check.loanerid == form.memberid.data: if form.attendtype.data == 'Unpaid': check.signin = form.attendtype.data db.session.commit() flash(' Student recorded successfully!') return render_template('loan_add.html', form=form, msgs=msgs) if form.attendtype.data == 'Paid': check.signout = form.attendtype.data db.session.commit() flash(' Student recorded successfully!') return render_template('loan.html', form=form, msgs=msgs) return render_template('loan_add.html', form=form, msgs=msgs)
def parse_into_loan(row): loan = Loan() for field in loan_csv_mapping: fieldname = field['fieldname'] parser = field['parser'] value = row[field['source_field']] setattr(loan, fieldname, parser(value)) return loan
def newloans(): from coinage import db from customers.models import Customer from models import Interest, Loan try: if not current_user.can_create: return redirect(url_for('loans.loans')) form = AddForm() _customer = Customer.query.with_entities(Customer.id, Customer.name).order_by(Customer.name) interest = Interest.query.order_by(Interest.value) form.customer_name.choices = form.comaker_name.choices = [(g.id, g.name) for g in _customer] form.interest.choices = [(g.value, g.name) for g in interest] if request.method == 'GET': form.interest.data = 5 form.payment.data = 0 form.total_payment.data = 0 if request.method == 'POST': if form.validate_on_submit(): try: loan = Loan() loan.customer_id = form.customer_name.data loan.date_release = request.form['date_rel'] loan.amount = Decimal(form.amount.data.replace(',', '')) loan.date_due = request.form['date_due'] loan.interest = form.interest.data loan.total_payable = Decimal(form.total_payable.data.replace(',', '')) loan.payment = Decimal(form.payment.data.replace(',', '')) loan.total_payment = Decimal(form.total_payment.data.replace(',', '')) loan.outstanding_balance = Decimal(form.outstanding_balance.data.replace(',', '')) db.session.add(loan) db.session.commit() flash(u'Record was successfully created.', 'success') return redirect(url_for('loans.loans')) except Exception as e: flash(e.message, 'danger') else: flash(form.errors, 'danger') return render_template("addloan.html", form=form) except TemplateNotFound: abort(404)
def loan_create(): labels = ["贷款号*", "身份证号*", "贷款金额*", "贷款银行*"] names = ["loanID", "cusID", "money", "bank"] init_form = {item: '' for item in names} if request.method == 'GET': return render_template('loan/create.html', init_form=init_form, labels=labels, names=names) if request.method == 'POST': errors = [] loanID = request.form['loanID'] cusID = request.form['cusID'] money = request.form['money'] bank = request.form['bank'] state = 'waiting' if len(loanID) != 4: errors.append('loanID') try: money = float(money) except: errors.append('money') if len(bank) == 0 or len(bank) > 20 or Bank.query.filter_by( bankname=bank).first() is None: errors.append('bank') if Loan.query.filter_by(loanID=loanID).first(): errors.append('loanID') if not Customer.query.filter_by(cusID=cusID).first(): errors.append('cusID') if not errors: new_loan = Loan(loanID=loanID, settime=datetime.now(), money=money, rest_money=money, bank=bank, state=state) db.session.add(new_loan) new_cusforloan = Cusforloan(loanID=loanID, cusID=cusID) db.session.add(new_cusforloan) db.session.commit() flash('Create new loan ' + loanID + ' successfully!') return render_template('loan/create.html', errors=errors, init_form=init_form, labels=labels, names=names) else: return render_template('loan/create.html', errors=errors, init_form=request.form, labels=labels, names=names)
def read_loans(filename): with open(filename, "r") as csvfile: # Skip the first line of notes csvfile.next() loanStatsReader = csv.DictReader(csvfile) for row in loanStatsReader: # Make sure the row's not empty. This choice of field is arbitrary if not row["mths_since_last_delinq"]: continue row = {k: strip_whitespace(v) for k, v in row.items()} loan = Loan(row) db.session.add(loan) db.session.commit()
def addloan(): form = Newloan(loan_orgCode=current_user.orgCode) now = datetime.datetime.now() if request.method == 'POST' and form.validate_on_submit(): exist = MemberJoin.query.filter_by(memberid=form.memberid.data).first() if exist: db.session.add( Loan(amount=form.amount.data, date=now, status=form.attendtype.data, loan_orgcode=current_user.orgCode, loanerid=form.memberid.data, loan_colyear=now.year)) db.session.commit() flash(' Record successfully added!') return redirect(url_for('loan')) else: flash('Member is NOT active') return redirect(url_for('addloan')) return render_template('loan_add.html', form=form)
def test_get_loan_penalty(self): testcases = [ ('U', 100, 600, 600, 0), ('U', 100, 300, 300, 3), ('U', 100, 0, 0, 10), ('P', 100, 600, 600, 2), ] for category, cms, borrower_income_1, borrower_income_2, penalty in testcases: with self.subTest(category=category): loan = Loan() loan.fitch_product_category = category loan.cms = cms loan.borrower_income_1 = borrower_income_1 loan.borrower_income_2 = borrower_income_2 self.assertEqual(penalty, self.loan_exception.get_loan_penalty(loan))
def setUp(self): self.loan = Loan() self.loan.id = 1
def setUp(self): self.loan = Loan()
def init_data(db): print('Generating data ...') from models import Bank, Customer, Account, Saveacc, Checkacc, Cusforacc, Loan, Cusforloan, Department, Employee db.session.query(Cusforloan).delete() db.session.query(Cusforacc).delete() db.session.query(Saveacc).delete() db.session.query(Checkacc).delete() db.session.query(Loan).delete() db.session.query(Customer).delete() db.session.query(Account).delete() db.session.query(Employee).delete() db.session.query(Department).delete() db.session.query(Bank).delete() bank_data = fake_bank() for bank in bank_data: if not Bank.query.filter_by(bankname=bank['bankname']).first(): new_bank = Bank(**bank) db.session.add(new_bank) db.session.commit() department_data = fake_department() for department in department_data: if not Department.query.filter_by( departID=department['departID']).first(): new_depart = Department(**department) db.session.add(new_depart) db.session.commit() emp_data = fake_emp(department_data) for emp in emp_data: if not Employee.query.filter_by(empID=emp['empID']).first(): new_emp = Employee(**emp) db.session.add(new_emp) db.session.commit() cus_data = fake_cus(bank_data, emp_data) for cus in cus_data: if not Customer.query.filter_by(cusID=cus['cusID']).first(): new_cus = Customer(**cus) db.session.add(new_cus) db.session.commit() acc_data, cusforacc_data, saveacc_data, checkacc_data = fake_acc( bank_data, cus_data) for acc in acc_data: if not Account.query.filter_by(accountID=acc['accountID']).first(): new_acc = Account(**acc) db.session.add(new_acc) for cusforacc in cusforacc_data: if not Cusforacc.query.filter_by(accountID=cusforacc['accountID'], cusID=cusforacc['cusID']).first(): new_cusforacc = Cusforacc(**cusforacc) db.session.add(new_cusforacc) for saveacc in saveacc_data: if not Saveacc.query.filter_by(accountID=saveacc['accountID']).first(): new_saveacc = Saveacc(**saveacc) db.session.add(new_saveacc) for checkacc in checkacc_data: if not Checkacc.query.filter_by( accountID=checkacc['accountID']).first(): new_checkacc = Checkacc(**checkacc) db.session.add(new_checkacc) db.session.commit() loan_data, cusforloan_data = fake_loan(bank_data, cus_data) for loan in loan_data: if not Loan.query.filter_by(loanID=loan['loanID']).first(): new_loan = Loan(**loan) db.session.add(new_loan) for cusforloan in cusforloan_data: if not Cusforloan.query.filter_by(loanID=cusforloan['loanID'], cusID=cusforloan['cusID']).first(): new_cusforloan = Cusforloan(**cusforloan) db.session.add(new_cusforloan) db.session.commit() print('Generation finished !')
def test_broken_by_loan_current_ltv_lower(self): loan = Loan() loan.original_ltv = 3 loan.current_ltv = 1 self.assertFalse(self.loan_exception.broken_by_loan(loan))
def process(self, commit, *args, **kwargs): data = commit.data loan = Loan() loan.id = data.get("id") loan.open = data.get("open") loan.approved = data.get("approved") loan.position = data.get("position") loan.expiration = data.get("expiration") loan.amount = data.get("amount") loan.cosigner = data.get("cosigner") loan.model = data.get("model") loan.creator = data.get("creator") loan.oracle = data.get("oracle") loan.borrower = data.get("borrower") loan.callback = data.get("callback") loan.salt = data.get("salt") loan.loanData = data.get("loanData") loan.created = data.get("created") loan.descriptor = Descriptor(**data.get("descriptor")) loan.currency = data.get("currency") loan.status = data.get("status") # loan.commits.append(commit) commit.save() loan.save()
def test_broken_by_loan(self): loan = Loan() loan.original_ltv = 3 loan.current_ltv = 5 self.assertTrue(self.loan_exception.broken_by_loan(loan))
page_size = len(this_page['teams']) for k in range(page_size): if this_page['teams'][k]['id'] not in loan_teams[loan_ids[today] [i]]: loan_teams[loan_ids[today][i]].append( this_page['teams'][k]['id']) with open(loan_team_csv, 'wb') as csv_file: writer = csv.writer(csv_file) for key, value in loan_teams.items(): writer.writerow([key, value]) ''' crawling loans ''' for i in range(len(loan_ids[today])): _loan_id = loan_ids[today][i] try: response = forwardRequest( loan_each(_loan_id), 'crawling the ' + str(i + 1) + ' loan: ' + str(_loan_id) + ', ' + ' out of ' + str(len(loan_ids[today]))) except Exception as e: print str(e) continue _loan_json = json.loads(response.read())['loans'][0] for k in loan_features: if k not in _loan_json.keys(): _loan_json[k] = 'N/A' _loan = Loan(_loan_json) _loan.write(loan_csv, loan_features)
def loans(*args, **kwargs): if request.method == 'GET': loans = Loan. \ where('closed', False). \ join(table=Currency.__table__, one='{}.id'.format(Currency.__table__), operator='=', two='{}.currency'.format(Loan.__table__), type='left outer'). \ group_by('{}.id'.format(Loan.__table__), '{}.name'.format(Currency.__table__)). \ order_by_raw('created_at DESC NULLS LAST'). \ get( [ '{}.*'.format(Loan.__table__), '{}.name as currency_name'.format(Currency.__table__) ] ). \ serialize() loans_sum = 0.0 for loan in loans: value = loan['value'] if loan['currency_name'] != 'rub': value = replace_value_with_rate( value=value, current_currency=loan['currency_name'], target_currency='rub') loans_sum += value return app_response(data={'items': loans, 'sum': loans_sum}) elif request.method == 'POST': body = request.json value = body.get('value', 0.0) value = float(value) name = body.get('name', '') currency = request.args.get('currency', None) if currency is None: currency = Currency.where('name', 'rub').first().id user = kwargs.get('user_info') description = body.get('description', None) loan = Loan.create(name=name, value=value, currency=currency) purchase = Purchase.create(name=name, value=value, currency=currency, complete=True, creator=user.id, description=description, loan=loan.id) purchase = purchase.serialize() purchase['currency_name'] = Currency.where('id', currency).first().name purchase['loan_closed'] = False replace_balance(value=float(value) * (-1), currency=currency) if purchase['currency_name'] != 'rub': value = replace_value_with_rate( value=float(value), current_currency=purchase['currency_name'], target_currency='rub') return app_response(data={'item': purchase, 'rub_value': value}) elif request.method == 'PUT': body = request.json loan_id = body.get('id', None) value = body.get('value', 0.0) value = float(value) currency = request.args.get('currency', None) if currency is None: currency = Currency.where('name', 'rub').first().id user = kwargs.get('user_info') description = body.get('description', None) closed = body.get('closed', False) loan = Loan.where('id', loan_id).where('closed', False).first() if loan: purchase = False if closed: loan_pay_value = loan.value loan.value = 0 loan.closed = True else: if currency is not None and loan.currency != currency: body_currency = Currency.where('id', currency).first() value = replace_value_with_rate( value=float(value), current_currency=body_currency.name, target_currency=currency.name) if value <= 0: loan_pay_value = loan.value loan.value = 0 loan.closed = True elif value > loan.value: loan_pay_value = value - loan.value loan.value = value purchase = True else: loan_pay_value = loan.value - value loan.value = value loan.save() if purchase: coming = Purchase.create(name=loan.name, value=loan_pay_value, currency=currency, complete=True, creator=user.id, description=description, loan=loan.id) else: coming = ComingIns.create(name=loan.name, value=loan_pay_value, currency=currency, creator=user.id, description=description) coming = coming.serialize() coming['currency_name'] = Currency.where('id', currency).first().name coming['loan_closed'] = loan.closed if purchase: replace_balance(value=float(loan_pay_value) * (-1), currency=currency) else: replace_balance(value=float(loan_pay_value), currency=currency) if coming['currency_name'] != 'rub': loan_pay_value = replace_value_with_rate( value=float(loan_pay_value), current_currency=coming['currency_name'], target_currency='rub') return app_response(data={ 'item': coming, 'rub_value': loan_pay_value }) return app_response(data={})
def test_broken_by_loan(self): loan = Loan() loan.maturity_date = date(2017, 1, 1) loan.completion_date = date(2017, 1, 2) self.assertTrue(self.loan_exception.broken_by_loan(loan))
def loansModelInstance(request): l = Loan(key_name = 201149912, customer_account_key="ABCD", collateral_key = "201149912", advance_amt = 176021) l.state = "WA" l.zip = "98606" l.orig_upb = 232000 l.curr_upb = 232000 l.origination_date = datetime.strptime("2/1/2012","%m/%d/%Y").date() l.is_adjustable = False l.investor_code = "JPM" l.property_type_code = "SFR" l.lien_position = 1 l.original_ltv = 35.8310 l.original_cltv = 35.8310 l.fico_score = 741 l.purpose_code = "CO" l.occupancy_code = "O" l.doc_level_code = 3 l.debt_service_ratio = 20.8011040 l.cur_note_rate = 4.3750 l.corelogic_fraud_risk_score = 783 l.corelogic_collateral_risk_score = 323 l.Hiden = False l.save() l = Loan(key_name = 201149913, customer_account_key="ABCD", collateral_key = "201149913", advance_amt = 176021) l.state = "WA" l.zip = "98606" l.orig_upb = 232000 l.curr_upb = 232000 l.origination_date = datetime.strptime("2/1/2012","%m/%d/%Y").date() l.is_adjustable = False l.investor_code = "JPM" l.property_type_code = "SFR" l.lien_position = 1 l.original_ltv = 35.8310 l.original_cltv = 35.8310 l.fico_score = 741 l.purpose_code = "CO" l.occupancy_code = "O" l.doc_level_code = 3 l.debt_service_ratio = 20.8011040 l.cur_note_rate = 4.3750 l.corelogic_fraud_risk_score = 783 l.corelogic_collateral_risk_score = 323 l.Hiden = False l.save() return HttpResponse("Initial data was readed")
def newloans(): from coinage import db from customers.models import Customer from models import Interest, Loan try: if not current_user.can_create: return redirect(url_for('loans.loans')) form = AddForm() _customer = Customer.query.with_entities( Customer.id, Customer.name).order_by(Customer.name) interest = Interest.query.order_by(Interest.value) form.customer_name.choices = form.comaker_name.choices = [ (g.id, g.name) for g in _customer ] form.interest.choices = [(g.value, g.name) for g in interest] if request.method == 'GET': form.interest.data = 5 form.payment.data = 0 form.total_payment.data = 0 if request.method == 'POST': if form.validate_on_submit(): try: loan = Loan() loan.customer_id = form.customer_name.data loan.date_release = request.form['date_rel'] loan.amount = Decimal(form.amount.data.replace(',', '')) loan.date_due = request.form['date_due'] loan.interest = form.interest.data loan.total_payable = Decimal( form.total_payable.data.replace(',', '')) loan.payment = Decimal(form.payment.data.replace(',', '')) loan.total_payment = Decimal( form.total_payment.data.replace(',', '')) loan.outstanding_balance = Decimal( form.outstanding_balance.data.replace(',', '')) db.session.add(loan) db.session.commit() flash(u'Record was successfully created.', 'success') return redirect(url_for('loans.loans')) except Exception as e: flash(e.message, 'danger') else: flash(form.errors, 'danger') return render_template("addloan.html", form=form) except TemplateNotFound: abort(404)
def test_broken_by_loan_completion_before_maturity(self): loan = Loan() loan.maturity_date = date(2017, 1, 2) loan.completion_date = date(2017, 1, 1) self.assertFalse(self.loan_exception.broken_by_loan(loan))
def test_get_loan_penalty(self): loan = Loan() self.assertEqual(4, self.loan_exception.get_loan_penalty(loan))