It is always important to learn how to invest your money properly so that you do not need to worry about money after retirement.
Starting from this blog post, I am going to share how I used python to set up my own investment plan.
I will try to cover a few topics like:
- how to visualize the long term investment plan
- backtest dollar-cost averaging strategy for long-term investment
- backtest value averaging strategy for long-term investment
- compare different investment strategies for short-term investment
The jupyter notebooks can be downloaded here.
Investing money into anything is often involved with risk. Please do your own research before investing and be responsible for your own investment decisions.
I am just learning investment on my own and want to share some codes that I have written that might be useful for others.
The content here is only for informational purpose (instead of taking them as professional investment advice).
This blogpost contains a function that helps you visualize your long term investment plan.
Step 1: Calculate how much savings do you have for now and estimate how much you can save per year
Step 2: Think about how much money do you need after retirement
3,000 Euro/Month –> 36,000 Euro/Year
Assuming we can have 5% interest rate per year, then we need to accumulate at least 720,000 Euro before retirement (36,000/0.05 = 720,000)
Please also note that, assuming the inflation rate of 3% per year, the buying power of 3000 Euro in 2050 might only worth 1235 Euro in 2020. Please adjust the inflation rate by yourself when estimating how much money do you need after retirement
Step 3: Estmiate (roughly) how much money do you need to invest per year and calculate it’s long term return
# Import libraries from matplotlib import pyplot as plt import pandas as pd plt.style.use('bmh')
def calc_return_over_periods(initial_investment: int, investment_per_period: int, return_per_period: float, n_period: int, increase_investment_per_period: float = 0.00, invest_at_period_begin: bool = True) -> pd.DataFrame: """ This function calculates the overall rate of return across n periods given a certain return rate pre period :param initial_investment: Amount of initial investment :param investment_per_period: Amount of investment per period :param return_per_period: Assumed rate of return per period :param n_period: Total number of periods :param increase_investment_per_period: Increase the amount of investment by x for each period after the first investment period :param invest_at_period_begin: whether to invest at the begining of each period or not :return: dataframe contains the rate of return for n periods. """ df_result = pd.DataFrame() for i in range(n_period): if i == 0: if invest_at_period_begin: period_begin_investment = initial_investment + investment_per_period if not invest_at_period_begin: period_begin_investment = initial_investment df_result.loc[i, 'period_begin_investment'] = period_begin_investment df_result.loc[i, 'total_investment'] = period_begin_investment value = period_begin_investment * (1 + return_per_period) df_result.loc[i, 'value_by_next_period'] = value else: if invest_at_period_begin: period_begin_investment = investment_per_period * ((1 + increase_investment_per_period) ** i) if not invest_at_period_begin: period_begin_investment = investment_per_period * ((1 + increase_investment_per_period) ** (i - 1)) value += period_begin_investment df_result.loc[i, 'period_begin_investment'] = period_begin_investment df_result.loc[i, 'total_investment'] = (df_result.loc[i - 1, 'total_investment'] + df_result.loc[i, 'period_begin_investment']) value = value * (1 + return_per_period) df_result.loc[i, 'value_by_next_period'] = value df_result['return_by_next_period'] = df_result['value_by_next_period'] / df_result['total_investment'] - 1 return df_result.round(2) def plot_changes(df: pd.DataFrame, y1: str = 'total_investment', y2: str = 'value_by_next_period', xlabel: str = 'period', ylabel: str = 'value', title: str = 'Visualize your saving plan and its future value', target: int = None) -> None: """ This function visualizes the total investment and the total value of the investment plan across time :param df: A dataframe contains total investment and total value :param y1: Column name :param y2: Column name :param xlabel: X label :param ylabel: Y label :param title: Title of the graph :param target: Final value one wants to achieve :return: A plot """ plt.figure(figsize=(15, 5)) plt.plot(df[y1], label=y1) plt.plot(df[y2], label=y2) if target: plt.axhline(y=target, c='black', label='target value') plt.xlim([0, len(df[y1])-1]) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.legend() plt.show()
Imagine that you are around 30 years old and have some savings (e.g., 20k Euro), and you are determined to invest 10000 Euro each year in order to have enough money for your retirement.
If you invest your savings into a ETF (e.g., SP500), you are likely to get about 5% annual return on average.
If everything works well, you want to retire around 60, so about 30 years to go!
Let’s use the function above to check if we can have enough money saved for retirement in this case.
# Each period is a year # Assuming investing 20000 Euro initially initial_investment = 20000 # Assuming investing 10000 Euro in the begining of each year investment_per_period = 10000 # Assuming the average investment return rate is about 5% return_per_period = 0.05 # Assuming the plan lasts for 30 years n_period = 30 df_plan1 = calc_return_over_periods(initial_investment, investment_per_period, return_per_period, n_period) df_plan1
target_value = 720000 plot_changes(df_plan1, title='Case 1', target = target_value, xlabel='year')
Conguraturations! It seems that if you just stick to this plan, you will have enough money for your retirement.
Due to inflation and the increase of your salary, you might decided to save 2% more each year, let’s check how that is going to change the final value
# Each period is a year # Assuming investing 20000 Euro initially initial_investment = 20000 # Assuming investing 10000 Euro in the begining of each year investment_per_period = 10000 # Assuming the average investment return rate is about 5% return_per_period = 0.05 # Assuming the plan lasts for 30 years n_period = 30 # Assuming increase the amount of investment each year by 2% increase_investment_per_period = 0.02 df_plan2 = calc_return_over_periods(initial_investment, investment_per_period, return_per_period, n_period, increase_investment_per_period) df_plan2
plot_changes(df_plan2, title='Case 2', target=target_value, xlabel='year')
It seems that it only takes about 26 years instead of the 30 years in order to have enough savings for retirement. However, the return rate was reduced a bit due to the investment of more money at the later stage of this plan.
Let’s imagine that you are at your early 20s and just got your first job recently and do not have any savings for now.
From next month on, you will be able to save 500 each month.
# Each period is a month # No initial investment initial_investment = 0 # Invest 500 Euro at the end of each month investment_per_period = 500 # Assuming the average investment return rate is about 5% per year return_per_year = 0.05 return_per_period = (return_per_year + 1)**(1/12) - 1 # Assuming the plan lasts for 40 years n_years = 40 n_period = n_years*12 df_plan3 = calc_return_over_periods(initial_investment, investment_per_period, return_per_period, n_period, invest_at_period_begin=False) df_plan3
plot_changes(df_plan3, title='Case 3', target=target_value, xlabel='month')
Even with little amount of savings, you can still have enough money for your retirement by 60.
We can observe that, in Case 3, the rate of return looks way better than Case 1 and and Case 2. So start investing earlier is always a good idea!
Hope this post is useful for you to set up a long term investment plan :)
Starting from the next post, we are going to do some backtesting using the total return index of SP500.