Как просмотреть список кредитов в Python, чтобы создать график погашения?Python

Программы на Python
Anonymous
Как просмотреть список кредитов в Python, чтобы создать график погашения?

Сообщение Anonymous »

Я новичок в Python и пытаюсь создать график погашения для списка из 400 кредитов. Конечный результат содержит только кредит_id и остаток_баланса на конец каждого месяца до погашения кредита.
Я нашел сообщение о функции амортизации, и нужна помощь, как просмотреть мой список кредитов.
Мой список кредитов выглядит следующим образом:
Изображение

Ниже приведен код, который я сейчас использую:
def amortize(loan_id, principal, remaining_balance, interest_rate, years, annual_payments=12, start_date=date.today()):

pmt = -round(np.pmt(interest_rate/annual_payments, years*annual_payments, principal), 2)
# initialize the variables to keep track of the periods and running balances
p = 1
beg_balance = remaining_balance
end_balance = remaining_balance

while end_balance > 0:

# Recalculate the interest based on the current balance
interest = round(((interest_rate/annual_payments) * beg_balance), 2)

# Determine payment based on whether or not this period will pay off the loan
pmt = min(pmt, beg_balance + interest)
principal = pmt - interest

# Ensure additional payment gets adjusted if the loan is being paid off
end_balance = beg_balance - principal

yield OrderedDict([('Load ID', loan_id),
('Month',start_date),
('Period', p),
('Begin Balance', beg_balance),
('Payment', pmt),
('Principal', principal),
('Interest', interest),
('End Balance', end_balance)])

# Increment the counter, balance and date
p += 1
start_date += relativedelta(months=1)
beg_balance = end_balance

Я знаю, как применить функцию амортизации только к выбранной строке, но как мне написать цикл для всех моих списков?
(список — это имя моего фрейма данных кредита)
amo_schedule = pd.DataFrame(amortize(list['id'][0],
list['origination'][0],
list['remaining_balance'][0],
list['interest'][0]/100,
list['term'][0],
start_date=date(2020,11,1)))

При удалении индекса я получил сообщение об ошибке со следующим кодом.
test = pd.DataFrame(amortize(list['id'],
list['origination'],
list['remaining_balance'],
list['interest'],
list['term'],
start_date=date(2020,11,1)))

ValueError Traceback (most recent call last)
in
----> 1 test = pd.DataFrame(amortize(list['id'],
2 list['origination'],
3 list['remaining_balance'],
4 list['interest'],
5 list['term'],

~\Anaconda3\lib\site-packages\pandas\core\frame.py in __init__(self, data, index, columns, dtype, copy)
500 elif isinstance(data, abc.Iterable) and not isinstance(data, (str, bytes)):
501 if not isinstance(data, (abc.Sequence, ExtensionArray)):
--> 502 data = list(data)
503 if len(data) > 0:
504 if is_dataclass(data[0]):

in amortize(loan_id, principal, remaining_balance, interest_rate, years, annual_payments, start_date)
7 end_balance = remaining_balance
8
----> 9 while end_balance > 0:
10
11 # Recalculate the interest based on the current balance

~\Anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
1327
1328 def __nonzero__(self):
-> 1329 raise ValueError(
1330 f"The truth value of a {type(self).__name__} is ambiguous. "
1331 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Вернуться в «Python»