Pandas 复利资本化

Pandas capitalization of compound interests

我正在编写 pandas 中银行存款账户的模拟。 我卡在了复利(这是利息再投资的结果,所以下一期的利息就是本金加上之前累积的利息。)

到目前为止我有以下代码:

import pandas as pd
from pandas.tseries.offsets import MonthEnd
from datetime import datetime

# Create a date range
start = '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 data
df = pd.DataFrame(date_rng, columns=['Date'])

# Add column (EndOfMonth) - shows the last day of the current month
df['LastDayOfMonth'] = pd.to_datetime(df['Date']) + MonthEnd(0)

# Add columns for interest, Sasha, Artem, Total, Description
df['Debit'] = 0
df['Credit'] = 0
df['Total'] = 0
df['Description'] = ''

# Iterate through the DataFrame to set "IsItLastDay" value
for i in df:
    df['IsItLastDay'] = (df['LastDayOfMonth'] == df['Date'])

# Add the transaction of the first deposit
df.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 year
df['InterestPerDay'] = (df['Total'] * 0.11) / 365
df['InterestCumulative'] = ((df['Total'] * 0.11) / 365).cumsum()

# Change the order of columns
df = df[['Date', 'LastDayOfMonth', 'IsItLastDay', 'InterestPerDay', 'InterestCumulative', 'Debit', 'Credit', 'Total', 'Description']]

df.to_excel("results.xlsx")

输出文件看起来不错,但我需要以下内容:

  1. "InterestCumulative" 列在每个月的最后一天添加到 "Total" 列(复利)
  2. 在每个月的月初,应清除 "InterestCumulative" 列(因为利息已添加到本金中)。

我该怎么做?

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

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

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

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