import numpy as np import matplotlib.pyplot as plt # 設定參數 initial_investment = 800000 # 初始投資金額 monthly_investment = 11800 # 每月投資金額 years = 7 # 投資期限(年) simulations = 10000 # 蒙地卡羅模擬次數 expected_return = 0.07 # 年化預期收益率 volatility = 0.15 # 年化投資組合波動率 num_months = years * 12 # 投資期限(月) # 設定每月利息支付 monthly_interest_payment = 0 # 更改此值以考慮每月利息支付 interest_payment = [monthly_interest_payment] * num_months def monte_carlo_simulation(initial_investment, monthly_investment, expected_return, volatility, num_months, simulations, interest_payment=None): # 計算每月收益率 monthly_return = np.random.normal(expected_return / 12, volatility / np.sqrt(12), (simulations, num_months)) # 初始化投資組合價值 portfolio_values = np.zeros((simulations, num_months + 1)) portfolio_values[:, 0] = initial_investment for i in range(num_months): if interest_payment is not None: # 計算每期的貸款利息金額 interest_payment_i = interest_payment[i] else: interest_payment_i = 0 # 計算投資組合價值 portfolio_values[:, i + 1] = (portfolio_values[:, i] * (1 + monthly_return[:, i])) + monthly_investment - interest_payment_i return portfolio_values # 執行蒙地卡羅模擬 portfolio_values_initial_investment = monte_carlo_simulation(initial_investment, 0, expected_return, volatility, num_months, simulations, interest_payment) portfolio_values_regular_investment = monte_carlo_simulation(0, monthly_investment, expected_return, volatility, num_months, simulations) # 計算分位數 quantiles = [0.9, 0.75, 0.5, 0.25, 0.1] quantiles_initial_investment = np.quantile(portfolio_values_initial_investment, quantiles, axis=0) quantiles_regular_investment = np.quantile(portfolio_values_regular_investment, quantiles, axis=0) # 繪製期初單筆投入的增長圖 plt.figure() for q_values in quantiles_initial_investment: plt.plot(q_values, label=f'{int(q_values[-1])}') plt.xlabel('Months') plt.ylabel('Portfolio Value') plt.title('Initial Investment') plt.legend() plt.show() # 繪製定期定額投入的增長圖 plt.figure() for q_values in quantiles_regular_investment: plt.plot(q_values, label=f'{int(q_values[-1])}') plt.xlabel('Months') plt.ylabel('Portfolio Value') plt.title('Regular Investment') plt.legend() plt.show() # 計算定期定額投資優於期初單筆投資的次數 better_regular_investment = np.sum(portfolio_values_regular_investment[:, -1] > portfolio_values_initial_investment[:, -1]) print(f'在 {simulations} 次模擬中,定期定額投資優於期初單筆投資的次數:{better_regular_investment}')