熊猫的复利资本化

我正在用熊猫写一个银行存款账户的模拟。我被复利困住了(这是利息再投资的结果,所以下一个时期的利息是通过本金加上以前累积的利息来赚取的。)


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


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”列应该被清除(因为利息被添加到本金总和中)。

http://img4.mukewang.com/619374140001ea2a08290519.jpg

我怎样才能做到这一点?


桃花长相依
浏览 171回答 1
1回答

慕盖茨4494581

您将需要循环,因为您的总数会根据前面的行而变化,然后会影响后面的行。因此,您当前的利息计算是错误的。total = 0cumulative_interest = 0total_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 = 0df.Total = total_per_daydf.InterestPerDay = interest_per_daydf.InterestCumulative = cumulative_per_day不幸的是,这看起来更令人困惑,但当值依赖于以前的值时就会发生这种情况。根据您的确切要求,可能有一些很好的方法可以使用数学来简化这一过程,但除此之外,这就是您所拥有的。我已将其直接写入 stackoverflow,因此它可能并不完美。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python