Очень плохо знаком с программированием и пытался создать таблицу амортизации. Нашел здесь несколько замечательных вопросов и ответов, но теперь я застрял, пытаясь преобразовать результаты в файл CSV.
from datetime import date
from collections import OrderedDict
from dateutil.relativedelta import *
import csv
def amortization_schedule(rate, principal, period):
start_date=date.today()
#defining the monthly payment for a loan
payment = -float(principal / ((((1 + (rate / 12)) ** period) - 1) / ((rate / 12) * (1 + (rate / 12)) ** period)))
beg_balance = principal
end_balance = principal
period = 1
while end_balance > 0 and period <= 60 * 12:
#Recalculate the interest based on the current balance
interest_paid = round((rate / 12) * beg_balance, 2)
#Determine payment based on whether or not this period will pay off the loan
payment = round(min(payment, beg_balance + interest_paid), 2)
principal = round(-payment - interest_paid, 2)
yield OrderedDict([('Month', start_date),
('Period', period),
('Begin Balance', beg_balance),
('Payment', payment),
('Principal', principal),
('Interest', interest_paid),
('End Balance', end_balance)])
#increment the counter, date and balance
period +=1
start_date += relativedelta(months=1)
beg_balance = end_balance
Я пытался использовать эту ссылку как часть моего решения, но в итоге получился CSV, который выглядел следующим образом:
M,o,n,t,h
P,e,r,i,o,d
B,e,g,i,n, ,B,a,l,a,n,c,e
P,a,y,m,e,n,t
P,r,i,n,c,i,p,a,l
I,n,t,e,r,e,s,t
E,n,d, ,B,a,l,a,n,c,e
Вот мой код для преобразования в CSV.
for start_date, period, beg_balance, payment, principal,
interest_paid, end_balance in amortization_schedule(user_rate,
user_principal, user_period):
start_dates.append(start_date)
periods.append(period)
beg_balances.append(beg_balance)
payments.append(payment)
principals.append(principal)
interest_paids.append(interest_paid)
end_balances.append(end_balance)
with open('amortization.csv', 'w') as outfile:
csvwriter = csv.writer(outfile)
csvwriter.writerow(start_dates)
csvwriter.writerow(periods)
csvwriter.writerow(beg_balances)
csvwriter.writerow(payments)
csvwriter.writerow(principals)
csvwriter.writerow(interest_paids)
csvwriter.writerow(end_balances)
Любая помощь будет оценена!