熊猫复利资本化

时间:2019-02-22 17:09:59

标签: python pandas economics

我正在模拟一个熊猫银行存款帐户。 我受困于复合利息(这是利息再投资的结果,因此,下一期的利息将以本金加上先前累积的利息来赚取。)

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

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”列(因为利息已添加到本金中)。

enter image description here

我不知道该怎么做。

您对此有何想法? 在此先感谢!

2 个答案:

答案 0 :(得分:1)

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

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中,所以它可能并不完美。

答案 1 :(得分:1)

一种不太优雅的解决方案。

# Get the values for the first and last days of months respectively
first_days = df.groupby(by=df['Date'].dt.month, as_index=False).first()
last_days = df.groupby(by=df['Date'].dt.month, as_index=False).last()

print(df.loc[df['Date'].isin(first_days['Date']), 'InterestCumulative'])
print(df.loc[df['Date'].isin(last_days['Date']), 'Total'])

# Replace first day interest with 0s
df.loc[df['Date'].isin(first_days['Date']), 'InterestCumulative'] = 0

# Adds last day 'Interestcumulative' to 'Total'
df.loc[df['Date'].isin(last_days['Date']), 'Total'] = (
            last_days['Total']
            + last_days['InterestCumulative']
        ).values

print(df.loc[df['Date'].isin(first_days['Date']), 'InterestCumulative'])
print(df.loc[df['Date'].isin(last_days['Date']), 'Total'])
相关问题