为了账号安全,请及时绑定邮箱和手机立即绑定

熊猫的复利资本化

熊猫的复利资本化

桃花长相依 2021-11-16 17:03:53
我正在用熊猫写一个银行存款账户的模拟。我被复利困住了(这是利息再投资的结果,所以下一个时期的利息是通过本金加上以前累积的利息来赚取的。)到目前为止,我有以下代码:import pandas as pdfrom pandas.tseries.offsets import MonthEndfrom datetime import datetime# Create a date rangestart = '21/11/2017'now = datetime.now()date_rng = pd.date_range(start=start, end=now, freq='d')# Create an example data frame with the timestamp datadf = pd.DataFrame(date_rng, columns=['Date'])# Add column (EndOfMonth) - shows the last day of the current monthdf['LastDayOfMonth'] = pd.to_datetime(df['Date']) + MonthEnd(0)# Add columns for interest, Sasha, Artem, Total, Descriptiondf['Debit'] = 0df['Credit'] = 0df['Total'] = 0df['Description'] = ''# Iterate through the DataFrame to set "IsItLastDay" valuefor i in df:    df['IsItLastDay'] = (df['LastDayOfMonth'] == df['Date'])# Add the transaction of the first depositdf.loc[df.Date == '2017-11-21', ['Debit', 'Description']] = 10000, "First deposit"# Calculate the principal sum (It the summ of all deposits minus all withdrows plus all compaund interests)df['Total'] = (df.Debit - df.Credit).cumsum()# Calculate interest per day and Cumulative interest# 11% is the interest rate per yeardf['InterestPerDay'] = (df['Total'] * 0.11) / 365df['InterestCumulative'] = ((df['Total'] * 0.11) / 365).cumsum()# Change the order of columnsdf = df[['Date', 'LastDayOfMonth', 'IsItLastDay', 'InterestPerDay', 'InterestCumulative', 'Debit', 'Credit', 'Total', 'Description']]df.to_excel("results.xlsx")输出文件看起来不错,但我需要以下内容:“InterestCumulative”栏在每个月的最后一天添加到“Total”栏(复合利息)在每个月的开始,“InterestCumulative”列应该被清除(因为利息被添加到本金总和中)。我怎样才能做到这一点?
查看完整描述

1 回答

?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞

您将需要循环,因为您的总数会根据前面的行而变化,然后会影响后面的行。因此,您当前的利息计算是错误的。


total = 0

cumulative_interest = 0


total_per_day = []

interest_per_day = []

cumulative_per_day = []

for day in df.itertuples():

    total += day.Debit - day.Credit

    interest = total * 0.11 / 365

    cumulative_interest += interest


    if day.IsItLastDay:

        total += cumulative_interest


    total_per_day.append(total)

    interest_per_day.append(interest)

    cumulative_per_day.append(cumulative_interest)


    if day.IsItLastDay:

        cumulative_interest = 0


df.Total = total_per_day

df.InterestPerDay = interest_per_day

df.InterestCumulative = cumulative_per_day

不幸的是,这看起来更令人困惑,但当值依赖于以前的值时就会发生这种情况。根据您的确切要求,可能有一些很好的方法可以使用数学来简化这一过程,但除此之外,这就是您所拥有的。


我已将其直接写入 stackoverflow,因此它可能并不完美。


查看完整回答
反对 回复 2021-11-16
  • 1 回答
  • 0 关注
  • 170 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信